This is a migrated thread and some comments may be shown as answers.

Is is possible to mock a private method of a Static class?

2 Answers 99 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
David
Top achievements
Rank 1
David asked on 15 Jan 2014, 09:19 AM
I tried the following:

Mock.NonPublic.Arrange(StaticClass, "PrivatedMethod", Arg.IsAny<object>()).CallOriginal();

But as the Static class cannot be instantiated, I have to pass the class, never a variable and Arrange Syntax is not happy about it at all.

Is this intentional? I mean, Justmock does not tolerate mocking private method of static classes at all?

I've found two workarounds:
- Make the method public for temporary testing purposes.
- Make the static class singleton for temporary testing purposes.

This two workarounds are just fine for temporary testing but I cannot modify the class structure.

Any suggestion is welcomed.

2 Answers, 1 is accepted

Sort by
0
Accepted
Kaloyan
Telerik team
answered on 15 Jan 2014, 09:52 AM
Hi David,

Mocking a private static method/function is completely achievable with JustMock. For more details and some examples, please check this article for our online help documentation.

Further, I have prepared a simple demo for you:

Let's assume we have the following static class
public static class StaticClass
{
    public static void CallPrivate(object obj)
    {
        PrivateMethod(obj);
    }
    private static void PrivateMethod(object obj)
    {
         
    }
}

Now, we want to check if the PrivateMethod is being called from the CallPrivate method. To do this, I prepared the following test
[TestMethod]
public void ShouldArrangeForPrivateStaticMethod()
{
    Mock.NonPublic.Arrange(typeof(StaticClass), "PrivateMethod", ArgExpr.IsAny<object>())
        .CallOriginal().MustBeCalled();
 
    StaticClass.CallPrivate(1);
 
             edit:
    Mock.NonPublic.Assert(typeof(StaticClass), "PrivateMethod", ArgExpr.IsAny<object>());
}

I hope this helps.

Regards,
Kaloyan
Telerik
Share what you think about JustTrace & JustMock with us, so we can become even better! You can use the built-in feedback tool inside JustTrace, our forums, or our JustTrace or JustMock portals.
0
David
Top achievements
Rank 1
answered on 15 Jan 2014, 11:27 AM
It worked, thank you for the quick answer!
Tags
General Discussions
Asked by
David
Top achievements
Rank 1
Answers by
Kaloyan
Telerik team
David
Top achievements
Rank 1
Share this question
or