好下午

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

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;
   }
}
.

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

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>();
.

和主要期望

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

如何为扩展Metod getToken创建测试?

有帮助吗?

解决方案

Extension methods are just syntatic sugar for static methods. So what you really need is the ability to mock the static method here. Unfortunately this is not possible in Rhino Mocks.

See the following StackOverflow thread for more details

To mock a static method you need a mocking framework which actually uses the CLR profiler to intercept method calls. As the thread mentions TypeMock should be able to do this.

其他提示

It should be possible by creating Stub for the extension methods.

Extension methods in Mono 2.4 and RhinoMocks 3.5

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top