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
16 June. According to Wikipedia, In computer science, reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.
The prime purpose of unit testing is to separate the written code for testing and determine if it works as intended. Unit testing involves testing individual components of a software program or application. The main objective of this process is to check that all the individual units are working in an intended way.
Generally, no. A unit test should be used to test for the functionality of a unit. You should unit test methods on a class, not individual, automatic properties (unless you are overriding the getter or setter with custom behaviour).
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.
You asking the wrong question. A better question would be:
How do I stop testing internal state of the class?
But, if you utterly need this, there are couple of ways described in this relevant SO answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With