【问题标题】:@AutoConfigureMockMvc how to set message converters@AutoConfigureMockMvc 如何设置消息转换器
【发布时间】:2020-11-02 15:54:48
【问题描述】:

使用 @AutoConfigureMockMvc 时如何指定消息转换器?

考虑以下示例:

@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));
    }
}

如果我使用普通的 mockMvc 而不是 customMvc 则会出现以下异常,因为 MappingJackson2HttpMessageConverter 未注册:

Type = org.springframework.http.converter.HttpMessageNotWritableException

如果我使用 customMvc 那么测试是绿色的。所以我需要以某种方式将 MappingJackson2HttpMessageConverter 应用到 mockMvc,但我不知道如何。

请指教

【问题讨论】:

    标签: spring-boot spring-boot-test mockmvc spring-autoconfiguration


    【解决方案1】:

    基于https://github.com/spring-projects/spring-boot/issues/24000,正确的解决方案是同时使用@AutoConfigureMockMvc 和@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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-25
      • 2015-09-16
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      相关资源
      最近更新 更多