SpringMVC3.2.x整合Fastjson与Controller单元测试

SpringMVC与Fastjson整合至关简单,只要在pom引入fastjson包后,配置一下SpringMVC的messageConverter就能够使用了。web

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
	<mvc:message-converters register-defaults="true">
		<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean>
  	</mvc:message-converters>
</mvc:annotation-driven>

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="mediaTypes" >
        <value>
    	  json=application/json
    	  xml=application/xml
    	 </value>
    </property>
</bean>

可是若是在单元测试时,使用mockMvc测试controllerspring

private MockMvc mockMvc ;
    @Before
    	public void setUp(){
            PersonalController ctrl = this.applicationContext.getBean(PersonalController.class);
    	mockMvc = MockMvcBuilders.standaloneSetup(ctrl).build();
    }
    @Test
    public void testGet() throws Exception{
    	MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders
    					.get("/p/list.json","json")
    					.accept(MediaType.APPLICATION_JSON)
    					.param("param1", "x")
    					.param("param2", "y")
    				).andReturn();
    	int status = mvcResult.getResponse().getStatus();
    	System.out.println("status : "+status);
    	String result = mvcResult.getResponse().getContentAsString();
    	System.out.println("result:"+result);
    //	Assert.assertEquals("test get  ... ", "","");
    }

此时会报406错误,也就是HTTP 406,NOT ACCEPTABLE。这是由于在 MockMvcBuilders.standaloneSetup(ctrl).build()内部,使用默认的messageConverter对message进行转换。json

在此输入图片描述

在此输入图片描述 对的,这里的messageConverters没有读取你配置的messageConverter。mvc

在此输入图片描述

解决方法也很简单,只要引入SpringMVC默认的jackson依赖就能够了。之因此报406,是由于缺乏可用的消息转化器,spring默认的消息转化器都配置了Content-Type。若是个人请求头里指定了ACCEPT为application/json,可是因为没有能转换此种类型的转换器。就会致使406错误。app

补充一下,mockMvc测试的时候,使用standaloneSetup方式测试,也可指定MessageConverter或拦截器,添加方法以下(须要在xml装配须要注入的类):单元测试

XXController ctrl = this.applicationContext.getBean(XXController .class);
    		FastJsonHttpMessageConverter fastjsonMC = this.applicationContext.getBean(FastJsonHttpMessageConverter.class);
    		StringHttpMessageConverter stringMC = this.applicationContext.getBean(StringHttpMessageConverter.class);
    		MessageInterceptor inter = this.applicationContext.getBean(MessageInterceptor.class);
    		mockMvc = MockMvcBuilders.standaloneSetup(ctrl)
    				.setMessageConverters(fastjsonMC,stringMC)
    				.addInterceptors(inter)
    				.build();
相关文章
相关标签/搜索