I am trying to create a test of a Spring Boot controller using TestRestTemplate. It is a requirement that only what is absolutely required for the controller be included in the test context, so spinning up the entire application context for the test is not an option.
Currently the test fails due to the endpoint returning 404. The endpoint works correctly in production. It appears that the controller is not being registered with the web servlet.
The controller appears as follows:
@RestController
class MyController {
@GetMapping("/endpoint")
fun endpoint(): ResponseDto {
return ResponseDto(data = "Some data")
}
}
data class ResponseDto(val data: String)
The test is as follows:
@SpringBootTest(
classes = [MyController::class, ServletWebServerFactoryAutoConfiguration::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
internal class MyControllerTestRestTemplateTest(
@Autowired private val restTemplate: TestRestTemplate
) {
@Test
fun `should work`() {
val result = restTemplate.getForEntity("/endpoint", String::class.java)
result.body.shouldMatchJson(
"""
{
"data": "Some data"
}
""")
}
}
How can I get this test setup to work?
It is a requirement that only what is absolutely required for the controller be included in the test context,...
SpringBoot has a tooling for that already - see @WebMvcTest
slice documentation or this SO answer.