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?
One way is to setup integrated web environment using
@WebMvCtest and then importWebConfigclass:Another way is to manually add
WebConfigto the standalone setup usingsetControllerAdvicemethod ofMockMvcBuilders: