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.
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.
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.
Since static method belongs to the class, there is no way in Mockito to mock static methods.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With