Spring MockRestServiceServer处理多个异步请求 [英] Spring MockRestServiceServer handling multiple Async requests

查看:402
本文介绍了Spring MockRestServiceServer处理多个异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Orchestrator Spring Boot服务,该服务对外部服务发出几个异步Rest请求,我想模拟那些服务的响应.

I have an orchestrator spring boot service that makes several async rest requests to external services and I would like to mock the responses of those services.

我的代码是:

 mockServer.expect(requestTo("http://localhost/retrieveBook/book1"))
    .andExpect(method(HttpMethod.GET))
    .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
        .body("{\"book\":{\"title\":\"xxx\",\"year\":\"2000\"}}")
            .contentType(MediaType.APPLICATION_JSON));

mockServer.expect(requestTo("http://localhost/retrieveFilm/film1"))
    .andExpect(method(HttpMethod.GET))
    .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK)
        .body("{\"film\":{\"title\":\"yyy\",\"year\":\"1900\"}}")
            .contentType(MediaType.APPLICATION_JSON));

service.retrieveBookAndFilm(book1,film1);
        mockServer.verify();

retrieveBookAndFilm服务调用两种异步方法,一种方法是检索书本,另一种方法是检索电影,问题在于有时会先执行电影服务,但会出现错误:

The retrieveBookAndFilm service calls two methods asynchronous one to retrieve the book and the other to retrieve the film, the problem is that sometimes the films service is executed first and I get an error:

java.util.concurrent.ExecutionException:java.lang.AssertionError:预期请求URI: http://localhost/retrieveBook/book1 ,但是是: http://localhost/retrieveFilm/film1

有什么主意我该如何解决这个问题,当执行此url并返回this或that时,是否有类似于mockito的说法?

Any idea how can I solve this issue, is there something similar to mockito to say when this url is executed then return this or that?

谢谢 问候

推荐答案

我遇到了同一问题,发现它是由两件事引起的

I ran into the same issue and found it was caused by two things

  1. 默认的MockRestServiceServer会按照您定义请求的顺序发出请求.您可以这样创建MockRestServiceServer来解决此问题:

MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build()

  1. (可能)为了两次使用相同的URI,请使用mockServer.expect(ExpectedCount.manyTimes(),RequestMatcher)方法来构建响应.

mockServer.expect(ExpectedCount.manyTimes(), MockRestRequestMatchers.requestTo(myUrl)) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(createResponse())

mockServer.expect(ExpectedCount.manyTimes(), MockRestRequestMatchers.requestTo(myUrl)) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(createResponse())

我通过结合其他两个答案找到了解决方案,这可能会提供更多信息.

I found the solution through the combination these two other answers which might offer more information.

如何将MockRestServiceServer与多个URL一起使用?

Spring MockRestServiceServer处理对相同的URI(自动发现)

这篇关于Spring MockRestServiceServer处理多个异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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