如何使用起订量来模拟扩展方法? [英] How do I use Moq to mock an extension method?

查看:137
本文介绍了如何使用起订量来模拟扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个测试,取决于扩展方法的结果,但我不希望扩展方法的未来未能打破过这个测试。嘲讽这个结果似乎是显而易见的选择,但起订量似乎并没有提供一种方式来覆盖静态方法(一个用于扩展方法要求)。没有与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 });

对于任何TypeMock迷们可能会建议我用隔离来代替:我AP preciate因为它看起来像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.

推荐答案

扩展方法是变相的只是静态方法。像起订量或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.

这篇关于如何使用起订量来模拟扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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