【问题标题】:is it possible to mock/fake an extension method?是否可以模拟/伪造扩展方法?
【发布时间】:2012-01-30 13:24:02
【问题描述】:

我正在使用控制器扩展,并尝试使用 FakeItEasy (v 1.7.4) 模拟它,如下所示:

A.CallTo(() => controller.RenderView(A<string>.Ignored,A<object>.Ignored,null)).Returns("");

但我收到此错误:

System.NullReferenceException : Object reference not set to an instance of an object.
at System.Object.GetType()
at FakeItEasy.Creation.ProxyGeneratorSelector.MethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget, ref String failReason)
at FakeItEasy.Configuration.DefaultInterceptionAsserter.AssertThatMethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget)
at FakeItEasy.Configuration.FakeConfigurationManager.CallTo(Expression`1 callSpecification)

【问题讨论】:

    标签: asp.net-mvc unit-testing moq fakeiteasy


    【解决方案1】:

    这是不可能的。 FakeItEasy(和其他流行的免费框架,如 Moq 或 RhinoMocks)使用的代理/拦截库不允许拦截静态方法(实际上是静态属性、密封类和非虚拟实例方法)。而扩展方法只是一种静态方法。

    你可以看看TypeMockJustMock,它们确实有这样的功能。

    【讨论】:

    【解决方案2】:

    如果扩展方法在单独的程序集中声明,您可以链接到具有相同命名空间的替换程序集。

    不过,您也必须替换此程序集中的任何其他必需类型。

    【讨论】:

    【解决方案3】:

    在 FakeItEasy 中,您可以将其创建为严格的模拟,然后配置静态方法

    http://hocke.blogspot.com.ar/2011/03/extension-method-for-creating-strict.html

    【讨论】:

    • 这与伪造扩展方法完全无关。你的 google-foo 让你失望了
    猜你喜欢
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多