如何使用 Rhino Mock 模拟扩展方法?
我已经扩展了 IDataReader 类型的对象以及我需要的一些扩展方法。现在的问题是,当我尝试模拟 IDataReader 时,扩展方法不包含在模拟中,因此当行 Expect.Call(reader.ExtensionMethod()).Return(someValue)
到达时ExtensionMethod
被执行,这不是我想要的!我希望记录该调用,并且当从其他地方调用扩展方法时,我希望它返回 someValue
。
有谁知道如何解决这个问题?
I have extended objects of type IDataReader with some extension methods that I needed. The problem is now when I try to mock the IDataReader, the extended method is not included in the mock so when the row Expect.Call(reader.ExtensionMethod()).Return(someValue)
is reach the ExtensionMethod
is executed which is not what I want! I want that call to be record and when the extension method is call from somewhere else I want it to return someValue
.
Does anyone know how to get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
披露:我为 Telerik 工作。
扩展方法实际上是隐藏为实例方法的静态方法。 RhinoMock 无法模拟静态方法,并且您也无法做到这一点,除非您使用另一个使用探查器的模拟库。
这样的库是 Telerik 的 JustMock。
Disclosure: I work for Telerik.
Extension methods are in fact static methods concealed as instance methods. RhinoMock cannot mock static methods and there's no way you can do it, unless you use another mocking library, which uses a profiler.
Such a library is JustMock by Telerik.
目前看来答案是否定的。糟糕的是,但我通过为我想要模拟的界面编写模拟类解决了我的问题。由于我不需要那么多接口方法,所以速度非常快。
The answer seems to be no at the moment. To bad though, but I solved my problem with writing a mock class for my interface I wanted to mock instead. Since I didn't needed that many methods of the interface it went pretty fast.
可以在没有任何框架的情况下存根扩展方法或任何其他静态方法。以下代码允许您执行此操作,您只需存根
_doSumm
即可。It is possible to stub extension method or any other static method without any framework. The following code allows you to do so, you just need to stub
_doSumm
.在我自己的实例中,我将必须存根的扩展方法包装到辅助类的方法中,该类在新接口中公开了包装器方法。我切换了生产代码以注入此帮助程序类的实例,并更改了代码以调用新方法。单元测试正在注入一个方便制作的辅助接口存根。
虽然这个解决方案并不完美,但它仍然没有交换模拟框架那么引人注目。
In my own instance, I wrapped the extension methods I had to stub into methods of a helper class that exposed the wrapper methods in a new interface. I switched my production code to have an instance of this helper class injected and changed the code to call the new methods. The unit tests are injecting a conveniently crafted stub of the helper interface.
While this solution is not perfect, it is still less dramatic than swapping the mocking framework.