Trying to Mock static class weird behaviour

2 posts, 0 answers
  1. Javier
    Javier avatar
    10 posts
    Member since:
    Apr 2013

    Posted 07 Jan 2014 Link to this post

    Hi, 

    I am trying to Mock a static method from a class that is static too,

    This static method calls another statics method of the same class,

    example:

    public static string MethodStaticA()
    {
         
        return MethodStaticB();
    }
    public static string MethodStaticB()
    {
        //Make something
    }


    For some reason when I try to Mock method A like this:

    Mock.SetupStatic(typeof(MfsUtils));
    

    Mock.Arrange(() => MfsUtils.MethodStaticA()).Returns("MyString");
    
    I can see in the logs that actually is calling to MethodStaticB() and I do not want to call it
    
    How can we properly  mock this??
  2. Kaloyan
    Admin
    Kaloyan avatar
    872 posts

    Posted 08 Jan 2014 Link to this post

    Hi Javier,

    Thank you for contacting us.

    I tried the following:
    public static class MfsUtils
    {
        public static string MethodStaticA()
        {
            return MethodStaticB();
        }
        public static string MethodStaticB()
        {
            throw new NotImplementedException();
        }
    }

     and the test:
    [TestMethod]
    public void TestMethod1()
    {
        // Arrange
        Mock.SetupStatic(typeof(MfsUtils), Behavior.CallOriginal);
     
        Mock.Arrange(() => MfsUtils.MethodStaticA()).Returns("MyString");
     
        // Act
        var actual = MfsUtils.MethodStaticA();
     
        // Assert
        Assert.AreEqual("MyString", actual);
    }

    On my side, this does not throw a NotImplementedException(). Further, I also used Behavior.Strict in the Mock.SetupStatic and again the test didn't throw StrictMockException for non arranged call to the MethodStaticB(). Another thing i tried was to assert the occurrences of the MethodStaticB method, with:
    Mock.Assert(() => MfsUtils.MethodStaticB(), Occurs.Never()); -> this passed.
    Finally, I completely dropped the Mock.SetupStatic and again I was not able to reproduce the issue.

    Can you please, send us the logs you mentioned in your ticket for further investigation? Also, providing your project may help a lot. You should be able to attach an archive of it to your next reply.

    Thank you for the help in advance.

    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
Back to Top