Moq-如何模拟Web服务调用? [英] Moq - How to mock web service call?
本文介绍了Moq-如何模拟Web服务调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的using
击中了一个我不想实际击中的外部资源.我想测试someResult
以及使用它的代码,但是每次我运行单元测试时,该代码仍然尝试访问真正的Web服务.如何使用moq伪造对Web服务的真实调用,而不在使用过程中模拟其余代码?
The using
below hits an external resource that I do not want to actually hit. I want to test someResult
and the code that uses it, but every time I run my unit test, this code still tries to hit the real web service. How do I use moq to fake the real call to the web service, but not mock the rest of the code within the using?
public IMyInterface.SomeMethod()
{
// hits a web service
using ( mySoapClient client = new mySoapClient() )
{
var someResult = client.DoSomething();
...
...
}
}
[TestMethod()]
public void SomeMethodTest()
{
IMyInterface target = new MyInterface();
target.SomeMethod();
// Assert....
}
推荐答案
您需要将Web服务实现与使用者分离开来
You need to decouple the web service implementation from the consumer
public class ClassIWantToTest
{
public ClassIWantToTest(IServiceIWantToCall service) {}
public void SomeMethod()
{
var results = service.DoSomething();
//Rest of the logic here
}
}
现在,您可以使用Moq来模拟IServiceIWantToCall
,以测试SomeMethod
Now you can use Moq to mock the IServiceIWantToCall
in order to test the logic of SomeMethod
这篇关于Moq-如何模拟Web服务调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文