Spring MockRestServiceServer处理多个异步请求

End*_*ika 4 junit spring-boot mockserver

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

我的代码是:

 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();
Run Code Online (Sandbox Code Playgroud)

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

java.util.concurrent.ExecutionException:java.lang.AssertionError:请求URI预期:HTTP://本地主机/ retrieveBook / BOOK1却被:HTTP://本地主机/ retrieveFilm / FILM1

任何想法我怎么解决这个问题,有什么类似mockito的说法,当执行此URL然后返回this或那个?

感谢和问候

小智 15

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

  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())

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

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

Spring MockRestServiceServer处理对同一URI的多个请求(自动发现)

  • 非常感谢MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build()的提示-它很有帮助! (2认同)