使用 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.
正确答案
起订量(和其他DynamicProxy-based 模拟框架)无法模拟任何不是虚拟或抽象方法的东西.
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 中称为 Fakes/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.
希望对您有所帮助.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanghficg
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22