简体   繁体   中英

Accessing internal class through reflection

Currently I wanted to do a UT coverage for which 100% function coverage is needed. I have a Public Class called FunctionParser.cs in my application and this internally uses an internal class called Autocomplete provided by Third party. Now the problem is there are few functionalities that lie within the AutoComplete Class which are untested . Therefore in order to do the coverage for this internal class named "AutoComplete" am trying to use reflection but nothing works for me can some one say me how can I use reflection to access this internal class for test purpose.

Note : I cannot modify the AutoComplete.CS which is an internal class provided by 3rd party, so other than using •Get [InternalsVisibleTo] . please suggest anything else that could work without modifying the third party class

var innerType = Assembly.GetExecutingAssembly().GetTypes()
                .Where(t => t.DeclaringType == typeof(Outer))
                .First(t => t.Name == "Inner");

var innerObject = Activator.CreateInstance(innerType);
innerType.GetMethod("InnerTest", BindingFlags.Instance | BindingFlags.NonPublic)
         .Invoke(innerObject, new object[] { });

--

public class Outer
{
    class Inner
    {
        internal void InnerTest()
        {
            Console.WriteLine("test");
        }
    }
}

You are not supposed to unit test code provided by third party. If your code is dependent on external code, then mock the behavior of that code. The external library may need encapsulation in additional class that implements special interface for example. Than inject that interface into your code for example in constructor. In the unit tests you will inject mocked implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM