How can I specify message converters when using @AutoConfigureMockMvc?
Consider following example:
@SpringBootTest(classes = SomeController.class)
@AutoConfigureMockMvc
@WithMockUser
class SomeControllerTestIT {
@Autowired
private MockMvc mockMvc;
@Autowired
private SomeController controller;
@Test
void foo() throws Exception {
MockMvc customMvc = standaloneSetup(resource).setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
customMvc.perform(get("/some-path"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE));
}
}
If I use plain mockMvc instead of customMvc then I get following exception, because MappingJackson2HttpMessageConverter is not registered:
Type = org.springframework.http.converter.HttpMessageNotWritableException
If I use customMvc then test is green. So I need to apply MappingJackson2HttpMessageConverter somehow to mockMvc, but I don't know how.
Please advise
Based on https://github.com/spring-projects/spring-boot/issues/24000 correct solution is using both @AutoConfigureMockMvc and @AutoConfigureWebMvc
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@AutoConfigureWebMvc
@AutoConfigureMockMvc
@WithMockUser
public @interface MockMvcWithUser {
}
@SpringBootTest(classes = SomeController.class)
@MockMvcWithUser
class SomeControllerTestIT {
... // same test logic goes here
}