如何使用 Moq 模拟 Web 服务调用? [英] How to mock web service call with Moq?

查看:45
本文介绍了如何使用 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屋!

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