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

Trying to Mock static class weird behaviour

1 Answer 17 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Javier
Top achievements
Rank 2
Javier asked on 07 Jan 2014, 03:01 PM
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??

1 Answer, 1 is accepted

Sort by
0
Kaloyan
Telerik team
answered on 08 Jan 2014, 10:01 AM
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.
Tags
General Discussions
Asked by
Javier
Top achievements
Rank 2
Answers by
Kaloyan
Telerik team
Share this question
or