2017-09-25 27 views
0

我有以下类型映射:春天开机MockMVC测试不使用自定义GSON型变换器,用于反序列化

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错误的请求,因为类型适配器没有用于反序列化。

请问缺少什么?

回答

0

你确定你没有得到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()); 
+0

这仅仅是我的问题一个错字时,我被简化我的例子。肯定是400由于数据序列化 – mangusbrother

+0

你可以发布你的POM? –

相关问题