Reflection for unit testing internal properties

c#, reflection, unit-testing

Solution

I agree with other comments that you should try to redesign to avoid testing internal state, however I did try your code and it works fine for me (.Net 4 on VS2012).

My class library under test looks like this:

using System;

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

    public class TargetContainerDto
    {
        internal TargetContainerType Type
        {
            get;
            set;
        }

        public void Print()
        {
            Console.WriteLine(Type);
        }
    }
}

And the test program (a Console app) looks like this:

using System;
using System.Reflection;
using ClassLibrary;

namespace Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var test = new TargetContainerDto();
            setType(test, 1);
            test.Print();
        }

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

This prints out `Group`, as expected. If we can identify the differences between this and your actual code, we may be able to find the problem.

Problem

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

Original source

Related problems