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 模拟扩展方法?
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01