簡體   English   中英

Spring Boot MockMVC測試未使用自定義gson類型映射器進行反序列化

[英]Spring boot MockMVC test not using custom gson type mapper for deserialization

我有以下類型映射器:

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


}

我的網絡配置:

@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錯誤的請求,因為類型適配器不用於反序列化。

請缺少什么?

您確定沒有收到404嗎? 我在這里https://github.com/Flaw101/gsonconverter重新創建了您的項目,並驗證了它的正常工作,但由於path參數中的大寫而不是測試,因此您的設置是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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM