Java Spring boot MockMVC测试未使用自定义gson类型映射器进行反序列化

Java Spring boot MockMVC测试未使用自定义gson类型映射器进行反序列化,java,spring,spring-boot,junit,gson,Java,Spring,Spring Boot,Junit,Gson,我有以下类型的映射器: public class LocaleTwoWaySerializer implements JsonSerializer<Locale>, JsonDeserializer<Locale> { @Override public JsonElement serialize(final Locale src, final Type typeOfSrc, final JsonSerializationContext context) {

我有以下类型的映射器:

public class LocaleTwoWaySerializer implements JsonSerializer<Locale>, JsonDeserializer<Locale> {
    @Override
    public JsonElement serialize(final Locale src, final Type typeOfSrc, final JsonSerializationContext context) {
        return src == null ? JsonNull.INSTANCE : new JsonPrimitive(src.getLanguage());
    }

    @Override
    public Locale deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
        return json == null || JsonNull.INSTANCE.equals(json) ? null : new Locale(json.getAsString());
    }
}
我的Web配置:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
    @ConditionalOnMissingBean
    @Autowired
    public GsonHttpMessageConverter gsonHttpMessageConverter(final Gson gson) {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(gson);
        return converter;
    }

}
我的测试:

@SpringBootTest(webEnvironment = WebEnvironment.MOCK    )
@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
public class MyTestClassIT {


    @Autowired
    private MockMvc mvc;

    @Autowired
    private Gson gson;

    @Test
    public void updateLocale() throws Exception {
        Locale locale = Locale.ITALIAN;
        mvc.perform(patch("/mypath").contentType(MediaType.APPLICATION_JSON)
                .content(gson.toJson(locale))).andExpect(status().isOk());
    }

}
我正在测试的api具有以下特征:

@PatchMapping(path = "myPath")
    public ResponseEntity<Void> updateLocale(@RequestBody Locale preferredLocale)
@PatchMapping(path=“myPath”)
public ResponseEntity updateLocale(@RequestBody Locale preferredLocale)
我已经放置了断点,可以验证是否正在构造我的GsonHttpMessageConverter,并且在测试中使用自动连线的GSON实例直接进行序列化可以正常工作(使用我的typeAdapter) 但是,我收到了一个400错误的请求,因为类型适配器不用于反序列化


请问缺少什么?

您确定您没有收到
404
吗?我在这里重新创建了您的项目,并验证了它是否正常工作,除了您的设置,它是一个
404
,因为
路径
参数的大小写不在测试中

  mvc.perform(patch("/mypath").contentType(MediaType.APPLICATION_JSON)
            .content(gson.toJson(locale))).andExpect(status().isOk());
应该是

  mvc.perform(patch("/myPath").contentType(MediaType.APPLICATION_JSON)
            .content(gson.toJson(locale))).andExpect(status().isOk());

当我简化我的例子时,这只是我问题中的一个输入错误。由于数据序列化,肯定是400。你能发布你的POM吗?
  mvc.perform(patch("/myPath").contentType(MediaType.APPLICATION_JSON)
            .content(gson.toJson(locale))).andExpect(status().isOk());