Sping Boot MockMVC测试未使用自定义gson类型Map器进行反序列化

8dtrkrch  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(124)

我有以下类型Map器:

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

字符串
我的GsonConfig:

@Configuration
public class GsonConfig {

    private static Gson GSON = generateStaticBuilder().create();

    private static GsonBuilder generateStaticBuilder() {
        return new GsonBuilder()
                                    .registerTypeAdapter(Locale.class, new LocaleTwoWaySerializer())
                                    .enableComplexMapKeySerialization()
                                    .setPrettyPrinting()
    }

    @Bean
    public Gson getGsonInstance() {
        return GSON;
    }

}


我的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)


我已经放置了断点,可以验证我的GsonHttpMessageConverter正在构造中,并且在我的测试中使用自动连接的GSON示例直接进行序列化工作正常(使用我的typeAdapter),但是我得到了一个400错误的请求,因为类型适配器没有用于反序列化。
请问缺少什么?

6xfqseft

6xfqseft1#

您确定您不会获得404吗?我在这里重新创建了您的项目https://github.com/Flaw101/gsonconverter,并验证了它的工作,除了与您的设置它是一个404,因为大写的path参数,这是不在测试中。

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());

相关问题