Registering WebMvcConfigurer for MockMvc test

105 Views Asked by At

I have a spring boot backend API where I use the following Configuration to do some formatting on the payload received by the API.

@Configuration
class WebConfig : WebMvcConfigurer {
    override fun addFormatters(registry: FormatterRegistry) {
        registerSpringFormatters(registry) //This is a custom method I wrote
    }
}

Now I need to write a unit test to test whether the input received to my controller is formatted correctly. I have written the following test for this.

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!!,
        )
    }
}

However, my test fails as the WebConfig being not registered during the test. How can I get my test to work with input properly formatted with the WebConfig?

1

There are 1 best solutions below

0
Elyorbek Ibrokhimov On

One way is to setup integrated web environment using @WebMvC test and then import WebConfig class:

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

Another way is to manually add WebConfig to the standalone setup using setControllerAdvice method of MockMvcBuilders:

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