Consider a controller built using RestController,
package starter.main.content
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class StarterController {
@GetMapping("/")
fun sayHello(): String {
return "Hello"
}
}
Testing with @SpringBootTest & TestRestTemplate
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
class IntegrationTest(@Autowired val testRestTemplate: TestRestTemplate) {
@Test
fun shouldReturnHello() {
val response = testRestTemplate.getForEntity<String>("/")
assertEquals(HttpStatus.OK, response.statusCode)
assertEquals("hello", response.body)
}
}
Warning
TestRestTemplate
 is only auto-configured whenÂ@SpringBootTest
 has been configured with aÂwebEnvironment
, meaning it starts the web container and listens for HTTP requests.
Testing with @SpringBootTest & MockMvc
@SpringBootTest
@AutoConfigureMockMvc
class IntegrationTest(@Autowired val mockMvc: MockMvc) {
@Test
fun shouldReturnHello() {
this.mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andDo(print())
.andExpect(status().isOk)
.andExpect(content().string("hello"))
}
}
@AutoConfigureMockMvc is essential
AutoConfigureMockMvc creates a MockMvc instance and injects it into the test class constructor
Testing with @WebMvcTest & MockMvc
@WebMvcTest(StarterController::class)
class IntegrationTest(@Autowired val mockMvc: MockMvc) {
@Test
fun shouldReturnHello() {
this.mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andDo(print())
.andExpect(status().isOk)
.andExpect(content().string("hello"))
}
}
Supply class(es) to @WebMvcTest
- WebMvcTest was introduced because @SpringBootTest is slow as it loads the entire application context before testing, without passing any classes, @WebMvcTest does the same!
- When you do supply a class, only the beans needed for it are loaded
Related
- SpringBootTest vs WebMvcTest
- Integration Testing RestController that calls a Service in SpringBoot Kotlin
- Unit Testing RestController that calls a Service in SpringBoot Kotlin