问题描述
我如何单元测试业务层的方法,使得调用WCF服务
How do I unit test a Business Layer method that makes call to WCF service?
例如:
public void SendData(DataUnit dataUnit)
{
//this is WCF call
SomeServiceClient svc = new SomeServiceClient();
svc.SomeMethod(dataUnit);
}
有没有一种方法,我可以在我的单元测试嘲笑SomeServiceClient ?项目
Is there a way I can mock SomeServiceClient in my Unit test project?
推荐答案
在这里你的问题是,你有紧耦合业务层到你的WCF服务 - 你真正创建一个新的实例业务层中的服务客户端,这意味着它现在已经不可能调用SendData方法而不同时调用服务的方法。
Your problem here is that you have tightly coupled your Business Layer to your WCF service - you actually create a new instance of the service client within the Business Layer, meaning that it is now impossible to call the SendData method without also calling the service methods.
这里最好的解决方案是引入依赖注射到你的架构。
The best solution here is to introduce dependency injection to your architecture.
在最简单的,你要做的就是通过你的服务类的一个实例到你的业务层。这通常是在一流的施工时间利用构造函数的参数完成的。
At its simplest, all you do is pass an instance of your service class into your Business Layer. This is often done at class construction time using a constructor parameter.
public class BusinessClass
{
private ISomeServiceClient _svc;
public BusinessClass(ISomeServiceClient svc)
{
_svc = svc;
}
public void SendData(DataUnit dataUnit)
{
_svc.SomeMethod(dataUnit);
}
}
请注意,上面的代码是一个设计模式,与在像控制容器的反转任何框架完全没有依赖。
Note that the code above is a design pattern, with absolutely no reliance upon any framework like an Inversion of Control container.
如果这是你的公司不使用这些框架(顺便说一个疯狂的策略)策略,您可以还是手动注入单元测试里面的服务您的模拟实例。
If it is your company's policy not to use such frameworks (an insane policy by the way), you can still manually inject your mock instances of the service inside your unit tests.
这篇关于单元测试调用WCF服务的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!