简体   繁体   English

使用moq模拟静态类

[英]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? 我在NUnit的帮助下编写单元测试用例并且有一些我需要模拟运行测试用例的静态类,所以我们可以在MOQ模拟框架的帮助下模拟静态类吗?

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. 有两种方法可以实现这一点 - 正如PSGuy所说,您可以创建一个代码可以依赖的接口,然后实现一个简单地调用静态方法或任何其他日志记录实现(如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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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