1

We have endpoints of the form:

@GetMapping("/myurl")
public Callable<String> getARandomString(@RequestParam int a) {

The application is configured with just one thread (that's why we use Callables to handle this). However, in order to create the tests for this, we do the setup as follows:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {MyApplication.class, MyController.class})
@ActiveProfiles("test")
public class MyControllerTest {

    @MockBean
    private MyService myService;

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.webAppContextSetup(wac)
                .build();

        when(myServices.isOk()).thenReturn(true);
    }

    @Test
    public void given_when_then() throws Exception {

        MvcResult mvcResult = mockMvc.perform(get("/myurl")
                .param("a", 1))
                .andExpect(request().asyncStarted())
                .andReturn();

        mvcResult.getAsyncResult();

        mockMvc
                .perform(asyncDispatch(mvcResult))
                .andExpect(status().isOk());
    }

1 test at the time works perfect. On the contrary, when having more than 1 test an exception as the following is thrown:

java.lang.IllegalStateException: Async result for handler [public java.util.concurrent.Callable<String> com.antmordel.MyController. getARandomString(int)] was not set during the specified timeToWait=0

I reckon that it is something about the timeouts. Have anybody had this issue?

AntMor
  • 417
  • 6
  • 18

1 Answers1

1

I had the exactly same problem. 01 test = OK, multiple tests in 01 run = FAIL.

Fixed by telling the TestRunner to consider that the current test makes the context "dirty".

Add @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) to your test class

See this question Reload Spring application context after every test

randrade86
  • 346
  • 1
  • 10