框架:spring boot
场景: 对一个controller做单元测试时出现如下异常信息:
java.lang.IllegalArgumentException: Content-Type cannot contain wildcard type '*'
相关UT代码:
RequestBuilder requestBuilder =MockMvcRequestBuilders.get("/apiname/"+apiparameters) .contentType(MediaType.APPLICATION_JSON_UTF8); MockHttpServletResponse response = mockMvc.perform(requestBuilder) .andReturn().getResponse();
接口介绍:
名称:/apiname/{apiparameters}
返回值类型:List
分析:
- 当接口返回值为String时,接口正常
- 从异常信息来看应该时springboot在json反序列化时,不能含有通配符,需要用户自己配置。
public void setContentType(@Nullable MediaType mediaType) { if (mediaType != null) { Assert.isTrue(!mediaType.isWildcardType(), "Content-Type cannot contain wildcard type '*'"); Assert.isTrue(!mediaType.isWildcardSubtype(), "Content-Type cannot contain wildcard subtype '*'"); set(CONTENT_TYPE, mediaType.toString()); } else { remove(CONTENT_TYPE); } }
debug到这个函数发现参数mediaType时*/*, 会直接断言进来。所以需要用户在自己项目里配置相关信息。
解决方案(相关代码从网络获取):
方案1: 自定义转化器,使用@bean注入fastJsonHttpMessageConverters到spring容器中
@Bean//使用@Bean注入fastJsonHttpMessageConvert public HttpMessageConverters fastJsonHttpMessageConverters() { //1.需要定义一个convert转换消息的对象; FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //2:添加fastJson的配置信息; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue); //3处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); //4.在convert中添加配置信息. fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; return new HttpMessageConverters(converter); }
方案2:在继承WebMvcConfigurerAdapter的类中重写(覆盖)configureMessageConverters方法
@Configuration public class FastJsonConfiguration implements WebMvcConfigurer{ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); //1.需要定义一个convert转换消息的对象; FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); //2.添加fastJson的配置信息,比如:是否要格式化返回的json数据; FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); //4.在convert中添加配置信息. fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); //5.将convert添加到converters当中. converters.add(fastJsonHttpMessageConverter); } }