我有一个 Spring Boot 后端 API,我使用以下配置对 API 收到的有效负载进行一些格式化。
@Configuration
class WebConfig : WebMvcConfigurer {
override fun addFormatters(registry: FormatterRegistry) {
registerSpringFormatters(registry) //This is a custom method I wrote
}
}
现在我需要编写一个单元测试来测试控制器接收到的输入格式是否正确。我为此编写了以下测试。
class MyApiControllerTest {
private val myService: OrderedProjectVintagesService = mock()
private val myController = MyController(
myService = myService
)
private lateinit var mockMvc: MockMvc
@Test
fun `test comma in attributes`() {
val input = Request(
projectTypes = listOf("type1,2"),
)
val sortedSummaries = listOf(
Summary(
currentPrice = BigDecimal("35"),
projectName = "Project 1"
)
)
whenever(
myService.listProjects(
projectTypes = input.projectTypes!!
)
).thenReturn(sortedSummaries)
mockMvc = MockMvcBuilders
.standaloneSetup(productItemOrderingController)
.build()
mockMvc.perform(
get("/api/ordered-projects")
.param("projectTypes", "type1,2")
).andExpect(status().isOk)
verify(myService, times(1)).listProjects(
projectTypes = input.projectTypes!!,
)
}
}
但是,我的测试失败了,因为测试期间未注册 WebConfig。如何让我的测试能够使用 WebConfig 正确格式化的输入?
一种方法是使用
@WebMvC
测试设置集成 Web 环境,然后导入 WebConfig
类:
@WebMvcTest(MyController::class)
@Import(WebConfig::class)
class MyControllerTest {
//...
}
另一种方法是使用
WebConfig
的 setControllerAdvice
方法手动将 MockMvcBuilders
添加到独立设置中:
val webConfig = WebConfig()
mockMvc = MockMvcBuilders
.standaloneSetup(myController)
.setControllerAdvice(webConfig)
.build()