如何在 Rhino Mocks 3.6 中将 Expect 设置为扩展方法
下午好,
我有一堂课,它有一个关联的扩展方法。
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>();
,主要的期望是
_interface.Expect(x => x.GetPersonInfo(2))
.Return(new Person { ID=2, Name = "A Stubbed Monica!" });
如何为扩展方法GetToken创建测试?
Good afternoon
I have a class and it has an associated extension method.
public class Person{
public int ID {get;set}
public string Name {get;set}
}
Extension method:
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;
}
}
Now I am trying to use Rhino and test this method
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
}
Supposing I am writing my test and have already an interface that calls GetPersonInfo()
var _interface = MockRepository.GenerateMock<IMyInterface>();
and the main Expect is
_interface.Expect(x => x.GetPersonInfo(2))
.Return(new Person { ID=2, Name = "A Stubbed Monica!" });
how can I create a test for the extension metod GetToken?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扩展方法只是静态方法的语法糖。所以你真正需要的是能够在这里模拟静态方法。不幸的是,这在 Rhino Mocks 中是不可能的。
有关更多详细信息,请参阅以下 StackOverflow 线程
使用 Rhino.Mocks模拟 模拟静态方法您需要一个模拟框架,该框架实际上使用 CLR 分析器来拦截方法调用。正如该线程提到的,TypeMock 应该能够做到这一点。
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.
通过为扩展方法创建存根应该可以实现。
Mono 2.4 和 RhinoMocks 3.5 中的扩展方法
It should be possible by creating Stub for the extension methods.
Extension methods in Mono 2.4 and RhinoMocks 3.5