简体   繁体   中英

Internal static class contains private class. How to create object of private class for unit testing using microsoft fakes

I searched a lot regarding this issue but did not get any issue same as I'm looking for, finally asking the question.

I'm using microsoft fakes to test the below C# code.

I'm stuck in a situation where I have a below class to test

 internal static class IntStaticClass
 {

     //some code

    private class PvtClass
    {
        public string Create(Obj1 o1, Obj2 o2)
        {

        //some code

        }
    }
}

Now I want to test create method.

However PrivateObject or PrivateType is not able to find typeof(MyPrivateClass)

Please help me how can I create the object of PvtClass and invoke the method create to test.

Thanks in advance.

You can get a reference to the outer class via Assembly.GetType() method, and from there the inner class can be accessed by Type.GetNestedTypes(BindingFlags.NonPublic)

The least painful way to get a reference to the assembly is typeof( some public class in that assembly ).Assembly .

Big ton of thanks to Joshua. Finally solved the issue. Cheers.

I wrote below code to create the instance of inner private class & execute the method of it.

            var type = typeof(IntStaticClass);
            var types = type.GetNestedTypes(BindingFlags.NonPublic);
            MethodInfo methodInfo = types[0].GetMethod("Create");
            object classInstance = System.Activator.CreateInstance(types[0], null);
            object[] parametersArray = new object[2] { new Obj1(), new Obj2() };
            var result = methodInfo.Invoke(classInstance, parametersArray);

Now able to test the method. Cheers.

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