Spring mvc 單元測試Demo
阿新 • • 發佈:2019-02-14
以前用struts框架的時候,給HTTP介面做測試,只能在瀏覽器上拼url和引數測,十分麻煩,而且不能自動化。但是用了Spring mvc之後,這種狀況改變了。spring-test模組對spring mvc的介面提供了良好的單元測試框架支援。有了這個框架,便可以對HTTP介面進行自動化單元測試了。對產品迭代開發的重要意義不言而喻。
首先我們需要新增spring-test的依賴。
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.0.RELEASE</version> <scope>test</scope> </dependency>
DEMO
package com.jd.service.waiter; import java.io.UnsupportedEncodingException; import lombok.extern.slf4j.Slf4j; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.jd.dd.mall.web.controller.waiter.OrgManageController; /** * @auther lvsheng * @date 2016年3月28日 * @time 下午2:00:41 * @project dd-mall-web * */ @Slf4j @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "classpath:spring-context.xml", "classpath*:/WEB-INF/spring-servlet.xml" }) public class OrgControllerTest { @Autowired OrgManageController orgManageController; @Autowired WebApplicationContext context; MockMvc mockMvc; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(orgManageController).build(); } @Test public void add() { try { ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("http://127.0.0.1/zb.waiter/16/org/"). accept(MediaType.APPLICATION_JSON). param("name", "武昌"). param("fid", "0"). param("tree_level", "2"). param("route", "1-"). param("mall_name", "眾包客服"). param("is_leaf", "true")); MvcResult mvcResult = resultActions.andReturn(); System.out.println("status :\t" + mvcResult.getResponse().getStatus()); String resposne = mvcResult.getResponse().getContentAsString(); System.out.println("reponse :\t" + resposne); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } catch (Exception e) { log.error(e.getMessage(), e); } } }
@ContextConfiguration註解既需要spring的配置檔案,同時需要spring mvc的配置檔案。MockMvc物件扮演一個客戶端呼叫的角色。這個物件需要在Test執行前構建好。