如何使用 Moq 模拟扩展方法?

How do I use Moq to mock an extension method?(如何使用 Moq 模拟扩展方法?)
本文介绍了如何使用 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 模拟扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)