Reflection for internal testing of internal properties

I have an open class ( TargetContainerDto) that has 2 internal properties. An enumeration and a type that contains the value from this enumeration.

I am trying to use the unit test type, but I am 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;
}

TargetContainerDtohas more properties than Type, but they are publicly available, so testing them is fine. iconURLis a string defined TargetContainerDtoin depending on the type. 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 a testing method when I need to set the type value, but I get MethodAccessException. I think because I do not have access to the listing. How can I access the listing through reflection?

thank

+5
3

, , , , (.Net 4 VS2012).

:

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);
        }
    }
}

( ) :

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);
        }
    }
}

Group, . , .

+1

InternalsVisibleTo, dll.

. AssemblyInfo.cs DLL :

[assembly:InternalsVisibleTo("TestAssembly")]

. .

+7

. :

?

But if you really need it, there are several ways described in this important SO answer

+6
source

All Articles