spring 为MockMvc测试注册WebMvcConfigurer

vof42yt1  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(36)

我有一个spring Boot 后端API,我使用以下Configuration对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正确格式化的输入?

mpgws1up

mpgws1up1#

一种方法是使用@WebMvC测试设置集成的Web环境,然后导入WebConfig类:

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

字符串
另一种方法是使用MockMvcBuilderssetControllerAdvice方法手动将WebConfig添加到独立设置中:

val webConfig = WebConfig()
mockMvc = MockMvcBuilders
     .standaloneSetup(myController)
     .setControllerAdvice(webConfig)
     .build()

相关问题