How do I use Moq to mock an extension method?(如何使用 Moq 模拟扩展方法?)
问题描述
我正在编写一个依赖于扩展方法结果的测试,但我不希望该扩展方法未来的失败会破坏这个测试.模拟该结果似乎是显而易见的选择,但 Moq 似乎没有提供覆盖静态方法的方法(扩展方法的要求).Moq.Protected 和 Moq.Stub 也有类似的想法,但它们似乎没有为这种情况提供任何东西.我是否遗漏了什么,或者我应该以不同的方式解决这个问题?
I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but Moq doesn't seem to offer a way to override a static method (a requirement for an extension method). There is a similar idea with Moq.Protected and Moq.Stub, but they don't seem to offer anything for this scenario. Am I missing something or should I be going about this a different way?
这里是一个简单的例子,失败了通常的对不可覆盖成员的无效期望".这是一个需要模拟扩展方法的坏例子,但它应该这样做.
Here is a trivial example that fails with the usual "Invalid expectation on a non-overridable member". This is a bad example of needing to mock an extension method, but it should do.
public class SomeType {
int Id { get; set; }
}
var ListMock = new Mock<List<SomeType>>();
ListMock.Expect(l => l.FirstOrDefault(st => st.Id == 5))
.Returns(new SomeType { Id = 5 });
至于任何可能建议我使用 Isolator 的 TypeMock 爱好者:我很欣赏您的努力,因为看起来 TypeMock 可以蒙住眼睛和醉酒完成这项工作,但我们的预算不会很快增加.
As for any TypeMock junkies that might suggest I use Isolator instead: I appreciate the effort since it looks like TypeMock could do the job blindfolded and inebriated, but our budget isn't increasing any time soon.
推荐答案
扩展方法只是变相的静态方法.Moq 或 Rhinomocks 等模拟框架只能创建对象的模拟实例,这意味着模拟静态方法是不可能的.
Extension methods are just static methods in disguise. Mocking frameworks like Moq or Rhinomocks can only create mock instances of objects, this means mocking static methods is not possible.
这篇关于如何使用 Moq 模拟扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Moq 模拟扩展方法?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01