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


Refs

  1. https://gustavopeiretti.com/spring-boot-unit-test-rest-controller/
  2. https://stackoverflow.com/questions/39213531/spring-boot-test-unable-to-inject-testresttemplate-and-mockmvc