【问题标题】:How to mock the webservice response of RestTemplate? [duplicate]如何模拟 RestTemplate 的 web 服务响应? [复制]
【发布时间】:2017-12-08 14:05:48
【问题描述】:

我想在我的整个应用程序上编写一个集成测试,并且只想模拟一个特定的方法:RestTemplate,我用它来向外部 Web 服务发送一些数据并接收响应。

我想从本地文件中读取响应(模拟和模仿外部服务器响应,所以它总是一样的)。

我的本​​地文件应该只包含json/xml 响应,在生产中外部网络服务器会响应。

问题:如何模拟外部 xml 响应?

@Service
public class MyBusinessClient {
      @Autowired
      private RestTemplate template;

      public ResponseEntity<ProductsResponse> send(Req req) {
               //sends request to external webservice api
               return template.postForEntity(host, req, ProductsResponse.class);
      }
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

   @Test
   public void test() {
        String xml = loadFromFile("productsResponse.xml");
        //TODO how can I tell RestTemplate to assume that the external webserver responded with the value in xml variable?
   }
}

【问题讨论】:

标签: java spring unit-testing junit spring-test


【解决方案1】:

春天真好:

    @Autowired
    private RestTemplate restTemplate;

    private MockRestServiceServer mockServer;

    @Before
    public void createServer() throws Exception {
        mockServer = MockRestServiceServer.createServer(restTemplate);
    }

    @Test
    public void test() {
        String xml = loadFromFile("productsResponse.xml");
        mockServer.expect(MockRestRequestMatchers.anything()).andRespond(MockRestResponseCreators.withSuccess(xml, MediaType.APPLICATION_XML));
    }
【解决方案2】:

您可以为此实现像 Mockito 这样的模拟框架:

因此,在您的 resttemplate 模拟中,您将拥有:

when(restTemplate.postForEntity(...))
    .thenAnswer(answer(401));

并回答类似的实现:

private Answer answer(int httpStatus) {
    return (invocation) -> {
        if (httpStatus >= 400) {
            throw new RestClientException(...);
        }
        return <whatever>;
    };
}

更多阅读请关注Mockito

【讨论】:

  • OP 想要模拟原始的 Web 服务 XML 响应,而不是 RestTemplate 返回的已解析和实例化的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2021-06-19
相关资源
最近更新 更多