使用moq模拟静态类 [英] Mock Static class using moq

查看:171
本文介绍了使用moq模拟静态类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在NUnit的帮助下编写单元测试用例,并且需要模拟一些静态类来运行测试用例,以便我们可以在 MOQ 模拟框架的帮助下对静态类进行模拟吗? /p>

请提出建议,如果有人有想法.

解决方案

有两种方法可以实现此目的-正如PSGuy所说,您可以创建代码可以依赖的Interface,然后实现一个简单地调用静态方法的具体方法或其他任何日志记录实现(例如NLog).这是理想的选择.除此之外,如果您有许多需要调用静态方法的代码需要进行测试,则可以重构要模拟的静态方法.

假设您的静态类如下所示:

public static class AppLog
{
    public static void LogSomething(...) { ... }
}

您可以引入一个公共静态属性,它是上面提到的Interface的一个实例.

public static class AppLog
{
    public static ILogger Logger = new Logger();

    public static void LogSomething(...)
    {
        Logger.LogSomething(...);
    }
}

现在可以测试任何依赖于此静态方法的代码.

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
}

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
}

这篇关于使用moq模拟静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆