【发布时间】:2011-11-03 14:37:17
【问题描述】:
创建单元测试以测试我发送到 WCF 服务的参数的最佳方法是什么?
我有一个项目,其中有一个与我的 WCF 服务对话的存储库类。它看起来像这样:
public class MyRepository : IMyRepository
{
public Customer GetCustomer(int customerId)
{
var client = new MyWCFServiceClient();
MyWCFServiceCustomer customerWCF = client.GetCustomer(customerId);
Customer customer = ConvertCustomer(customerWCF);
return customer;
}
//Convert a customer object recieved from the WCF service to a customer of
//the type used in this project.
private Customer ConvertCustomer(MyWCFServiceCustomer customerWCF)
{
Customer customer = new Customer();
customer.Id = customerWCF.Id;
customer.Name = customerWCF.Name;
return customer;
}
}
(这显然是简化的)
现在我想编写单元测试来检查我从存储库发送到我的服务的参数是否正确。在上面的示例中,这有点毫无意义,因为我只在传入时发送 customerId,但在我的真实代码中,存储库类中有更多参数和更多逻辑。
问题是生成的服务客户端类(MyWCFServiceClient)没有接口,所以我不能在我的测试中模拟它(或者我错了吗?)。
编辑:我错了。有界面!请参阅下面的答案。
一种解决方案是拥有一个包装服务客户端的类,并且只重新发送参数并返回结果:
public class ClientProxy : IClientProxy
{
public MyWCFServiceCustomer GetCustomer(int customerId)
{
var client = new MyWCFServiceClient();
return client.GetCustomer(customerId);
}
}
public interface IClientProxy
{
MyWCFServiceCustomer GetCustomer(int customerId);
}
这样我可以给那个类一个接口,从而模拟它。但是编写那个“代理”类并保持更新似乎很乏味,所以我希望你有更好的解决方案! :)
【问题讨论】:
标签: .net wcf unit-testing