注册WebMvcConfigurer进行MockMvc测试

问题描述 投票:0回答:1

我有一个 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 正确格式化的输入?

spring spring-boot mocking spring-boot-test mockmvc
1个回答
0
投票

一种方法是使用

@WebMvC
测试设置集成 Web 环境,然后导入
WebConfig
类:

@WebMvcTest(MyController::class)
@Import(WebConfig::class)
class MyControllerTest {
   //...
}

另一种方法是使用

WebConfig
setControllerAdvice
方法手动将
MockMvcBuilders
添加到独立设置中:

val webConfig = WebConfig()
mockMvc = MockMvcBuilders
     .standaloneSetup(myController)
     .setControllerAdvice(webConfig)
     .build()
© www.soinside.com 2019 - 2024. All rights reserved.