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
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
}