我有一个 Orchestrator Spring Boot 服务,它向外部服务发出多个异步休息请求,我想模拟这些服务的响应。
我的代码是:
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 服务异步调用两个方法,一个检索书籍,另一个异步检索电影,问题是有时先执行电影服务,然后出现错误:
java.util.concurrent.ExecutionException:java.lang.AssertionError:预期请求URI:http://localhost/retrieveBook/book1但是是:http://localhost/retrieveFilm/film1
知道如何解决这个问题吗,有没有类似于mockito的东西说当这个url被执行时然后返回这个或那个?
谢谢 问候
我遇到了同样的问题,发现是由两件事引起的
MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build()
mockServer.expect(ExpectedCount.manyTimes(),
MockRestRequestMatchers.requestTo(myUrl))
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andRespond(createResponse())
我通过结合这两个其他答案找到了解决方案,这可能会提供更多信息。
使用mockServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();解决了问题