Skip to main content
 首页 » 编程设计

spring-boot之Spring MockRestServiceServer 处理多个异步请求

2024年05月29日37lyj

我有一个 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: Request URI expected:http://localhost/retrieveBook/book1 but was:http://localhost/retrieveFilm/film1

知道如何解决这个问题吗,是否有类似于mockito的东西说当这个url被执行时然后返回这个或那个?

谢谢 问候

请您参考如下方法:

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

  1. 默认的 MockRestServiceServer 期望请求按照您定义的顺序进行。您可以通过创建 MockRestServiceServer 来解决这个问题,如下所示:

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

  • (可能)为了两次使用相同的 URI,请使用mockServer.expect(ExpectedCount.manyTimes(), RequestMatcher) 方法来构建响应。
  • mockServer.expect(ExpectedCount.manyTimes(), MockRestRequestMatchers.requestTo(myUrl)) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(createResponse())

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

    How to use MockRestServiceServer with multiple URLs?

    Spring MockRestServiceServer handling multiple requests to the same URI (auto-discovery)