【发布时间】:2020-06-15 22:34:51
【问题描述】:
我正在尝试使用 TestRestTemplate 创建一个 Spring Boot 控制器的测试。要求只有控制器绝对需要的内容才能包含在测试上下文中,因此为测试启动整个应用程序上下文不是一种选择。
由于端点返回 404,当前测试失败。端点在生产中正常工作。控制器似乎没有注册到 web servlet。
控制器显示如下:
@RestController
class MyController {
@GetMapping("/endpoint")
fun endpoint(): ResponseDto {
return ResponseDto(data = "Some data")
}
}
data class ResponseDto(val data: String)
测试如下:
@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"
}
""")
}
}
我怎样才能让这个测试设置工作?
【问题讨论】:
-
您能否尝试从测试中的注释中删除
ServletWebServerFactoryAutoConfiguration。
标签: spring-boot kotlin spring-boot-test