Mock Static class using moq

走远了吗. 提交于 2020-01-13 09:22:11

问题


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.


回答1:


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
}


来源:https://stackoverflow.com/questions/46801776/mock-static-class-using-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!