C# – Reflection for unit testing internal properties

creflectionunit testing

I have a public class(TargetContainerDto) that has 2 internal properties. An enum and a type that contains a value from that enum.

I'm trying to unit test the type, but I'm having problems.

internal enum TargetContainerType
{
    Endpoint,
    Group,
    User,
    UserGroup
}


internal TargetContainerType Type { get; set; }

This is my reflection code in my test class

public void setType(TargetContainerDto t, int val)
{
    BindingFlags bf = BindingFlags.NonPublic | BindingFlags.Instance;
    PropertyInfo pi = t.GetType().GetProperty("Type", bf);
    pi.SetValue(t, val, null);
}

public TargetContainerDto setTypeTo(TargetContainerDto t, int val)
{
    setType(t, val);
    return t;
}

TargetContainerDto has more properties than Type, but they are public so testing them is fine. The iconURL is a string defined in TargetContainerDto depending on what the type is. Here is my Testmethod:

public void DefaultSubGroupIcon()
{
    var o1 = new TargetContainerDto
    {
        Id = 1234,
        DistinguishedName = "1.1.1.1",
        SubGroup = "test",
    };
    setType(o1, 3);
    Assert.AreEqual(o1.IconUrl, "/App_Themes/Common/AppControl/Images/workstation1.png");
}

I call setTypeTo in test method when I need to set the typevalue, but I'm getting a MethodAccessException. I think it's because I don't have access to the enum. How can I access the enum through reflection?

Thanks

Best Answer

Mark your assembly with the InternalsVisibleTo attribute and you don't need to use reflection in your test dll.

e.g. in the AssemblyInfo.cs file in your application dll add the following line:

[assembly:InternalsVisibleTo("TestAssembly")]

see here for more details.