在使用spring mvc編寫接口服務時進行單元測試是頗有必要的,能夠減小接口的出錯率減小協同調試時間,尤爲是對於先後端分離的web應用,這種應用先後端分工明確。對於spring項目要是進行單元測試,只需集成spring-test便可,最好導入servlet api,不然可能出現相似錯誤java
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale zh_Cn
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
1.controller代碼web
@Controller @RequestMapping("user") public class UserController{ @Resource private UserService userService; @ResponseBody @RequestMapping(value="/add",method = RequestMethod.POST) public CommonResult save(User entity){ return userService.save(entity); } @ResponseBody @RequestMapping(value="/update",method = RequestMethod.POST) public CommonResult update(User entity){ return userService.update(entity); } @ResponseBody @RequestMapping(value="/delete/{id}",method = RequestMethod.GET) public CommonResult delete(@PathVariable int id){ return userService.delete(id); } @ResponseBody @RequestMapping(value="/query/{id}",method = RequestMethod.GET) public CommonResult queryById(@PathVariable int id){ return userService.queryById(id); } /** * 使用@RequestBody接收json數據 */ @ResponseBody @RequestMapping(value = "jsonContent",method = RequestMethod.POST) public CommonResult testJsonContent(@RequestBody User user){ System.out.println("user:"+JSON.toJSONString(user)); return new CommonResult(); } }
2.測試代碼:spring
//靜態導入 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; 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.web.context.WebApplicationContext; /** * controller restful接口單元測試 * * @author yu * @date 2016-12-30 21:24:57 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:spring-mybatis.xml", "classpath:spring-mvc.xml" }) public class UserControllerTest extends ControllerBaseTest { @Resource private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = webAppContextSetup(this.wac).build(); } /** * 測試controller add接口 * * @throws Exception */ @Test public void testAdd() throws Exception { MvcResult result = mockMvc.perform(post("/user/add") .contentType(MediaType.APPLICATION_JSON) .param("id", "1") .param("name", "zhangsan") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 測試controller queryById接口 * * @throws Exception */ @Test public void testQueryById() throws Exception { MvcResult result = mockMvc.perform(get("/user/query/{id}", 1) .contentType(MediaType.APPLICATION_JSON) .param("param1", "pm1") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 測試controller update接口 * * @throws Exception */ @Test public void testUpdate() throws Exception { MvcResult result = mockMvc.perform(get("/user/update") .contentType(MediaType.APPLICATION_JSON) .param("id", "1") .param("name", "list") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 測試controller delete接口 * * @throws Exception */ @Test public void testDelete() throws Exception { MvcResult result = mockMvc.perform(get("/user/delete/{id}", 1) .contentType(MediaType.APPLICATION_JSON) .param("param1", "pm1") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 測試發送content * @throws Exception */ @Test public void testSendJsonContent() throws Exception { User user = new User(); user.setId(1); user.setName("lisi"); String userJson = JSON.toJSONString(user);//發送json MvcResult result = mockMvc.perform(post("/user/jsonContent") .contentType(MediaType.APPLICATION_JSON) .content(userJson) ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } }
測試時加sessionjson
HashMap<String, Object> sessionattr = new HashMap<String, Object>(); sessionattr.put("username", "xyyy"); MvcResult result = mockMvc.perform(post("/news/add") // .sessionAttrs(sessionattr) .contentType(MediaType.APPLICATION_JSON)
注意:若是是測試類中只加載spring的配置,不加載spring mvc配置會致使@ResponseBody返回的值不能轉換成json(因此其實就是spring mvc配置文件中定義了數據裝換)而出現http status 406錯誤後端
@ContextConfiguration({"classpath:spring-mybatis.xml"})
這種狀況對於@RestController仍然能夠得到數據,可是須要從MvcResult中調用api
getModelAndView().getModel()
獲得數據。spring-mvc