简体   繁体   English

内部静态类包含私有类。 如何使用Microsoft Fake创建私有类的对象以进行单元测试

[英]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. 我正在使用Microsoft Fakes测试以下C#代码。

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) 但是,PrivateObject或PrivateType无法找到typeof(MyPrivateClass)

Please help me how can I create the object of PvtClass and invoke the method create to test. 请帮助我如何创建PvtClass对象并调用create方法进行测试。

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) 您可以通过Assembly.GetType()方法获取对外部类的引用,然后可以通过Type.GetNestedTypes(BindingFlags.NonPublic)访问内部类。

The least painful way to get a reference to the assembly is typeof( some public class in that assembly ).Assembly . 引用程序集的最简单的方法是typeof(该程序).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. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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