Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Static class using moq

Tags:

c#

.net

moq

nunit

I am writing unit test cases with the help of NUnit and have some static classes that I need to mock to run test cases so can we mock static class with the help of MOQ mocking framework?

Please suggest If some have idea.

like image 349
mahesh sharma Avatar asked Oct 18 '17 02:10

mahesh sharma


People also ask

Can you Moq a static class?

You can use Moq to mock non-static methods but it cannot be used to mock static methods. Although static methods cannot be mocked easily, there are a few ways to mock static methods.

How do you create a static class mock?

Mocking Static Methods If you need to truly mock static methods, you need to use a commercial tool like Microsoft Fakes (part of Visual Studio Enterprise) or Typemock Isolator. Or, you can simply create a new class to wrap the static method calls, which itself can be mocked.

Can you mock a static method?

Since static method belongs to the class, there is no way in Mockito to mock static methods.

How do you mock a static property?

As a solution you can create a wrapper class (Adapter Pattern) holding the static property and fake its members. Another solution is to use Isolation framework (as Typemock Isolator) in which you can fake static classes and members.


1 Answers

There are two ways to accomplish this - As PSGuy said you can create an Interface that your code can rely on, then implement a concrete that simply calls the static method or any other logging implementation like NLog. This is the ideal choice. In addition to this if you have lots of code calling the static method that needs to be tested you can refactor your static method to be mocked.

Assuming your static class looks something like this:

public static class AppLog
{
    public static void LogSomething(...) { ... }
}

You can introduce a public static property that is an instance of the Interface mentioned above.

public static class AppLog
{
    public static ILogger Logger = new Logger();

    public static void LogSomething(...)
    {
        Logger.LogSomething(...);
    }
}

Now any code dependent on this static method can be tested.

public void Test()
{
    AppLog.Logger = Substitute.For<ILogger>(); // NSubstitute

    var logMock = new Mock<ILogger>();         // Moq
    AppLog.Logger = logMock.Object;            // Moq 

    SomeMethodToTest();

    AppLog.Logger.Recieved(1).LogSomething(...); // NSubstitute

    logMock.Verify(x => x.LogSomething(...));    // Moq
}
like image 59
Aaron Roberts Avatar answered Oct 07 '22 07:10

Aaron Roberts