使用Rhino Mocks,如何拦截对接口上单个属性的调用,同时将其他所有内容传递给“默认实现”?
我有一个带有许多方法和属性的接口 IComplex,我希望创建一个“模拟”,使“Config”属性返回我选择的对象,同时将所有其他调用传递给“真实” IComplex 的实例。
只是为了让这个变得更难一点,我们仍然使用 C# V2!
I have an interface IComplex with many methods and properties, I wish to create a “mock” that makes the “Config” property return an object of my choose, while passing all other calls onto a “real” instance of IComplex.
Just to make this a bit harder we are still using C# V2!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要创建一个代理对象,它将所有调用传递到实际实现的实例 - 除非您想要覆盖成员的行为。
据我所知,Rhino Mocks 不支持这一点。但是,您也许可以使用 Castle 动态代理 自己构建类似的模拟功能图书馆。 (Rhino 模拟使用相同的库。)
You want to create a proxy object which passes all calls through to an instance of the real implementation - except when you want to override behavior of a member.
As far as I know, Rhino Mocks does not support this. However, you might be able to build a mocking feature like that yourself with the Castle Dynamic Proxy library. (Rhino mocks uses the same library.)
据我所知,没有一个功能可以同时配置多个mock方法。您需要指定所有方法以将它们转发到其他实现......
除非您编写一些反射代码来配置模拟。
这是一些(工作)代码。它使用 C# 3.0,但主要部分是为 C# 2.0 编写的“旧式”Rhino Mocks 内容。
用法:
As far as I know, there isn't a feature to configure many methods of mock at once. You need to specify all the methods to forward them to the other implementation...
... unless you write some reflection code to configure the mock.
Here is some (working) code. It uses C# 3.0, but the main part is "old style" Rhino Mocks stuff which had been written for C# 2.0.
Usage:
您可以使用
PartialMock
方法创建模拟。您将真实类的类型传递给此方法,并且仅注册需要模拟的调用。
请注意,您想要模拟 IComplex 实现的方法必须是虚拟的才能完成此操作。
请参阅http://www.ayende.com/wiki/Rhino+Mocks+ Partial+Mocks.ashx 了解更多信息。
You can use the
PartialMock
method to create a mock.You pass the type of the real class to this method and only register the calls that you need to mock.
Note that the methods you want to mock of the
IComplex
implementation need to be virtual to accomplish this.See http://www.ayende.com/wiki/Rhino+Mocks+Partial+Mocks.ashx for more information.