Reputation: 387
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.
Upvotes: 4
Views: 557
Reputation: 387
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.
Upvotes: 2
Reputation: 43327
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
.
Upvotes: 3