首页 > 解决方案 > MockRestServiceServer 看到先前测试的请求

问题描述

我正在运行 JUnit5,MockRestServiceServer并看到当我使用异步请求运行多个测试时,MockRestServiceServer测试 A 将看到来自测试 B 的请求并将其标记为意外。

@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
public class MyTestClass {

  @Autowired
  private RestTemplate restTemplate;
  @Autowired
  private WebApplicationContext wac;

  private MockRestServiceServer mockServer;
  private MockMvc mockMvc;

  private URI asyncUri = URI.create("/asyncUrl");

  @BeforeEach
  public void setUp(){
    mockerServer = MockRestServiceServer.bindTo(restTemplate).ignoreExpectOrder(true).build();
    mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
  }

  @AfterEach
  public void tearDown(){
    mockServer.verify();
    mockServer.reset();
  }

  @Test
  public void dontRunAsyncMethod(){
    mockServer.reset(); // Added trying to fix the issue
    mockServer.expect(ExpectedCount.never(), requestTo(asyncUri));

    URI uri = URI.create("/myApi?runAsyncMethod=false");
    mockMvc.perform(get(uri));
  }

  @Test
  public void doRunAsyncMethod(){
    mockServer.reset(); // Added trying to fix the issue

    // Side issue here - I have to use `between` rather than `times`
    // because mockServer validates before request happens
    mockServer.expect(ExpectedCount.between(0, 1), requestTo(asyncUri));

    URI uri = URI.create("/myApi?runAsyncMethod=true");
    mockMvc.perform(get(uri));
  }
}

单独运行时,两个测试都通过。但是,当我将它们一起运行时,dontRunAsyncMethod会失败,说没有预期的请求/asyncUrl。有没有办法更分离测试?在开始下一次测试之前,我能否以某种方式确保所有请求都已完成?

标签: spring-bootjunitmockrestserviceserver

解决方案


推荐阅读