简体   繁体   中英

Mock Static class using moq

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM