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

3 posts, 1 answers
  1. David
    David avatar
    2 posts
    Member since:
    Apr 2013

    Posted 15 Jan 2014 Link to this post

    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. Answer
    Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 15 Jan 2014 Link to this post

    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.
  3. DevCraft R3 2016 release webinar banner
  4. David
    David avatar
    2 posts
    Member since:
    Apr 2013

    Posted 15 Jan 2014 Link to this post

    It worked, thank you for the quick answer!
Back to Top