用于客户端单元测试的模拟 Web 服务 [英] Mocking Web Services for client layer unit testing
问题描述
我有一个业务规则 Visual Studio 类库 (.NET 2.0) 项目,该项目依赖于 Dynamics Crm Web 服务 - 一个经典的 SOAP Web 参考,而不是 WCF 端点.我想对这些业务规则进行单元测试,而无需背后真正的 crm 实例.添加 Web 引用不会产生我可以伪造的界面.它确实在我的项目中生成了 c#,如果我可以创建接口,我认为我可以伪造.我认为我不需要实际浏览 HTTP 并了解所有协议内容.
I have a business rule visual studio class library (.NET 2.0) project that takes a dependency on Dynamics Crm Web Services - a classic SOAP web reference as opposed to a WCF endpoint. I want to unit test those business rules without having a real crm instance behind it. Adding a web reference doesn't produce an interface that I can fake. It does generate c# in my project that I think I can fake if I can create the interface. I don't think I need to actually navigate HTTP and get into all of the protocol stuff.
我看到了 Joh Skeet 的 博客文章.唉,我不想写任何代码,我希望从那时起编写了一个工具,这可能会有所帮助.我尝试了他的一些步骤,但得出的结论是他比我更聪明,我做不到.
I saw Joh Skeet's blog post. Alas I didn't want to write any code and I'm hoping a tool has been written since then that might help. I tried some of his steps but concluded that he is smarter than me and I couldn't make that work.
我知道 SoapUI,但是,我希望能够在 CI 构建环境中工作的纯单元测试.
I am aware of SoapUI, however, I was hoping for pure unit tests that would work in a CI build environment.
有没有办法做到这一点.
Is there a way to do this.
推荐答案
模拟没有接口的东西的标准方法是围绕它构建你自己的包装器.
The standard way to mock something which doesn't come with an interface, is to build your own wrapper around it.
你想模拟的代码,比如网络服务的东西:
the code you want to mock, say the webservice stuff:
class AutoGeneratedStuff
{
public string GeneratedMethodYouUse()
{...}
public string GeneratedMethodYouDontNeed()
{...}
}
然后你创建一个只包含你需要的代码的界面:
you then make an interface which covers only the bits of the code you need:
public interface IWebServiceClient
{
string MethodYouUse();
}
和一个实现它的具体包装类,它依赖于生成的东西
and a concrete wrapper class which implements it, which has a dependency to the generated stuff
class WebServiceClient : IWebServiceClient
{
private AutoGeneratedStuff _stuff;
public WebService(AutogeneratedStuff stuff)
{
_stuff = stuff;
}
public string MethodYouUse()
{
return _stuff.MethodYouUse();
}
}
然后,在您的代码中,当您调用生成的类时,改为调用您的接口.在您的单元测试中,您可以使用模拟框架来模拟接口,或者通过使用另一个与生成的东西没有依赖关系的具体类来实现接口
then, in your code when you would have called the generated class, call your interface instead. In your unit tests, you can mock the interface, either using a mocking framework, or by implementing the interface with another concrete class that has no dependencies to the generated stuff
这篇关于用于客户端单元测试的模拟 Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!