如何使用MOQ框架在c#中模拟静态方法? [英] How to mock static methods in c# using MOQ framework?

查看:198
本文介绍了如何使用MOQ框架在c#中模拟静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在进行单元测试,并且已经使用MOQ框架和MS Test成功地模拟了各种场景.我知道我们无法测试私有方法,但我想知道是否可以使用MOQ来模拟静态方法.

I have been doing unit testing recently and I've successfully mocked various scenarios using MOQ framework and MS Test. I know we can't test private methods but I want to know if we can mock static methods using MOQ.

推荐答案

Moq(以及其他基于DynamicProxy 的模拟框架)无法模拟非虚拟或抽象方法的任何东西.

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

只能使用基于Profiler API的工具来伪造密封/静态类/方法,例如 Typemock (商业)或Microsoft Moles(免费,在Visual Studio 2012 Ultimate中称为/2013/2015).

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

或者,您可以重构设计以抽象化对静态方法的调用,并通过依赖注入将这种抽象提供给您的类.然后,您不仅会有更好的设计,而且还可以通过Moq等免费工具进行测试.

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

可以完全允许使用可测试性的通用模式,而无需完全使用任何工具.请考虑以下方法:

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

您可以尝试将其包装在protected virtual方法中,而不必尝试模拟FileUtil.ReadDataFromFile

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

然后,在您的单元测试中,从MyClass派生并将其命名为TestableMyClass.然后,您可以覆盖GetDataFromFile方法以返回您自己的测试数据.

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

希望有帮助.

这篇关于如何使用MOQ框架在c#中模拟静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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