Reputation: 385
I'd like to ask a question which bother me a lot...
How can I mock the return value of MyPublicStaticMethod_C?? MyPrivateStaticClass_B is really private and static
public static partial class MyPublicStaticClass_A
{
private static partial class MyPrivateStaticClass_B
{
public static int MyPublicStaticMethod_C(string para)
{
//...
}
//...
}
}
Upvotes: 1
Views: 1077
Reputation: 14473
You must reference the private type through the reflection API using GetNestedType()
. Then you can use the non-public mocking API to arrange the method. Here's a working example:
public static partial class MyPublicStaticClass_A
{
public static int Test(string str)
{
return MyPrivateStaticClass_B.MyPublicStaticMethod_C(str);
}
private static partial class MyPrivateStaticClass_B
{
public static int MyPublicStaticMethod_C(string para)
{
return 1;
}
}
}
[TestMethod]
public void ShouldArrangeInnerPrivateClassMethod()
{
var privateType = typeof(MyPublicStaticClass_A).GetNestedType("MyPrivateStaticClass_B", BindingFlags.NonPublic);
Mock.NonPublic.Arrange<int>(privateType, "MyPublicStaticMethod_C").Returns(5);
var result = MyPublicStaticClass_A.Test(null);
Assert.Equal(5, result);
}
But, yeah, having such code should be a last resort - only if refactoring is impossible or unfeasible.
Upvotes: 2
Reputation: 4278
I'm going to be slightly unhelpful here and say that you shouldn't mock that. When writing tests you should only test your public interface, not your private. The private stuff is implementation specific and your tests shouldn't care about that.
If you have a public method that calls your private method and you feel that you need to mock the private method in order to properly test your class - that is a code smell. You should refactor your code and take in the inner private class as an interface, that way you can mock it.
If you do figure out a way to mock this in its current state, it will most likely not really give you a better tested system - however it will get you brittle tests that are hard to maintain.
Upvotes: 5