【问题标题】:How to set Expect to a Extension method in Rhino Mocks 3.6如何在 Rhino Mocks 3.6 中将 Expect 设置为扩展方法
【发布时间】:2011-03-30 15:43:17
【问题描述】:

下午好

我有一个类,它有一个关联的扩展方法。

public class Person{
    public int ID {get;set}
    public string Name {get;set}
}

扩展方法:

public static class Helper {
   public static int GetToken(this Person person){
       int id = 0;
       //Something here is done to read token from another service...
       return id;
   }
}

现在我正在尝试使用 Rhino 并测试此方法

public void readPersonToken(int personId) {

   var person = Person.GetPersonInfo(personId);//we consume a service here
   Console.Writeline(person.GetToken());//get token is consuming another service

}

假设我正在编写测试并且已经有一个调用 GetPersonInfo() 的接口

var _interface = MockRepository.GenerateMock<IMyInterface>();

而主要的Expect是

_interface.Expect(x => x.GetPersonInfo(2))
          .Return(new Person { ID=2, Name = "A Stubbed Monica!" });

如何为扩展方法 GetToken 创建测试?

【问题讨论】:

  • 很难准确了解这里发生了什么,尤其是有趣的部分是您从扩展方法中删除的代码。

标签: c# testing extension-methods rhino expectations


【解决方案1】:

扩展方法只是静态方法的语法糖。所以你真正需要的是在这里模拟静态方法的能力。不幸的是,这在 Rhino Mocks 中是不可能的。

有关详细信息,请参阅以下 StackOverflow 线程

要模拟静态方法,您需要一个实际使用 CLR 分析器拦截方法调用的模拟框架。正如线程提到的那样,TypeMock 应该能够做到这一点。

【讨论】:

    【解决方案2】:

    应该可以通过为扩展方法创建存根来实现。

    Extension methods in Mono 2.4 and RhinoMocks 3.5

    【讨论】:

      猜你喜欢
      • 2011-10-15
      • 2010-10-03
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多