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();
相關文章
相關標籤/搜索