I am running JUnit5 with MockRestServiceServer
and seeing that when I run multiple tests with async requests, the MockRestServiceServer
in test A will see a request from test B and flag as unexpected.
@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));
}
}
When run separately, both tests pass. However, when I run them together, dontRunAsyncMethod
will fail saying that no request was expected to /asyncUrl
. Is there a way to separate the tests more so? Can I somehow ensure that all requests have completed before beginning the next test?