模拟 WCF 服务的简单方法? [英] Easy way to mock a WCF service?

查看:33
本文介绍了模拟 WCF 服务的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 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();

我不能将代理传递给 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.通过这种方式,您可以替换工厂,为客户端提供一个创建模拟而不是真实代理的工厂.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆