I have a simple Spring Boot service that uses StreamingResponseBody to write the response. When testing this with MockMvc, the first test gives me the correct response, but the second one has an empty response body. However, when I add a little sleep time to the test, they both work.
Here is my controller (Kotlin)
@RestController
class DummyController() {
@GetMapping()
fun streamIndex() =
ResponseEntity.ok()
.contentType(MediaType.TEXT_PLAIN)
.body(StreamingResponseBody { it.write("Hello world".toByteArray()) })
}
And my tests:
@AutoConfigureMockMvc(print = MockMvcPrint.NONE)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DummyControllerTest {
private val controller = DummyController()
private val mvc = MockMvcBuilders.standaloneSetup(controller).setControllerAdvice(GlobalExceptionHandler()).build()
@Test
fun test1() {
mvc.perform(get("/")).andExpect(status().isOk).andExpect(content().string("Hello world"))
}
@Test
fun test2() {
mvc.perform(get("/")).andExpect(status().isOk).andExpect(content().string("Hello world"))
}
}
Thee first test succeeds, the second one fails with:
java.lang.AssertionError: Response content expected:<Hello world> but was:<>
Then when I add a little delay in the test it works:
@Test
fun test2() {
mvc.perform(get("/")).andExpect(status().isOk)
.andDo { Thread.sleep(5) }
.andExpect(content().string("Hello world"))
}
Is this a bug in MockMvc or something missing in my test?
Thanks in advance,
Rob