模拟WCF服务的简单方法? [英] Easy way to mock a WCF service?
问题描述
我有一个使用WCF服务的应用程序.现在,我想向应用程序添加单元测试.
I've got an app which is using a WCF service. Now I'd like to add unit tests to the app.
在某些情况下,我需要模拟WCF服务,因为有时很难从服务中获得所需的行为(例如,服务抛出特殊异常).
For some cases I need to mock the WCF service, since getting the desired behaviour from the service sometimes is tough (e.g. service throws special exceptions).
我可以向wcf客户端添加另一个接口,但这似乎有点愚蠢,因为客户端调用已经在使用接口了.
I could add yet another interface to the wcf client, but this seems a bit silly, since the client calls already are using an interface.
是否有一种简单的方法来模拟WCF服务?比创建另一个接口层并重定向其中的每个WCF调用更容易?
Is there an easy way to mock a WCF service? Easier than creating another interface layer and redirecting every single WCF call inside it?
大多数答案似乎对WCF服务的使用不太了解,因此需要澄清一下:
要从ViewModel使用WCF服务,我必须管理如下连接:
Most of the answers seem not to know much about WCF service using, so some clarification:
To use a WCF service from a ViewModel, I have to manage the connection something like this:
ChannelFactory<IMyWcfService> channelFactory = new ChannelFactory<IMyWcfService>("");
IMyWcfService proxy = channelFactory.CreateChannel();
proxy.CallMyStuff();
proxy.Close();
我不能只将ViewModel代理传递给WCF,因为需要为每个事务打开和关闭连接.因此,使用RhinoMock/NMock无效,因为它们需要一个将代理作为参数的ViewModel,如果使用WCF,则无法做到这一点.
I can't just pass the ViewModel the proxy to the WCF, since the connection needs to be opened and closed for every transaction. For this reason using RhinoMock/NMock would not work, since they need a ViewModel which gets the proxy as a parameter, which can't be done like this if you use WCF.
推荐答案
为什么不能使用 NMock2 直接模拟IMyWcfService
接口?
Why can't you use something like NMock2 to mock the IMyWcfService
interfaces directly?
如果需要能够即时创建新实例,请使用工厂"对客户端隐藏ChannelFactory<IMyWcfService>
.这样,您可以替换工厂,为客户端提供一个创建模拟而不是真实代理的
If you need to be able to create new instances on the fly, use the Factory to hide the ChannelFactory<IMyWcfService>
from the client. This way you can replace the factory, providing the client one which creates mocks instead of real proxies.
这篇关于模拟WCF服务的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!