SpringMVC單元測試之MockMVC,模擬登入使用者
阿新 • • 發佈:2019-02-08
今天介紹一下springMVC的單元測試,可以參考spring官方文件進行
前提準備,springmvc的demo工程,這裡就不做敘述了
pom.xml
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency>
controller層
package controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import service.UserService; import domain.User; /** * UserController. * @author Leon Lee */ @RestController @RequestMapping(value = "user") public class UserController { /** * UserService interface. */ @Autowired private UserService userService; /** * Get user MSG. * @param userId * @return user Msg */ @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.GET) public User getUserMsg(@PathVariable(value = "userId") String userId) { return userService.getUserMsg(userId); } /** * Update user MSG. * @param userId * @param userName * @return updated user MSG */ @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.PUT) public User putUserMsg(@PathVariable(value = "userId") String userId, @RequestParam String userName,HttpSession session){ if(null == (String)session.getAttribute("loginUser")) return new User(); System.out.println((String)session.getAttribute("loginUser")); return userService.putUserMsg(userId, userName); } /** * Delete user. * @param userId * @return deleted user MSG */ @RequestMapping(value = "userMsg/{userId}", method = RequestMethod.DELETE) public User delUserMsg(@PathVariable(value = "userId") String userId){ return userService.delUserMsg(userId); } /** * Add user. * @param userName * @return added user MSG */ @RequestMapping(value = "userMsg", method = RequestMethod.POST) public User postUserMsg(@RequestParam String userName){ return userService.postUserMsg(userName); } /** * login User. Note that do not send password as url. * @param userId * @param password * @return */ @RequestMapping(value = "userMsg/{userId}/{password}", method = RequestMethod.GET) public boolean loginUser(@PathVariable String userId, @PathVariable String password, HttpSession session){ if("loginUser".equals(userId)&&"loginUser".equals(password)){ session.setAttribute("loginUser", userId); return true; } return false; } }
單元測試類
這裡的靜態匯入比較重要,有時候沒辦法自動匯入的 就是下面的 import static xxx.* 另一點,@ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:applicationContext.mvc.xml"})
代表的是載入的配置檔案,可以根據需要進行新增
package controller.test; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import javax.servlet.http.HttpSession; 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.mock.web.MockHttpSession; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; /** * spring mvc Test. * @author Leon Lee * @since spring-4.1.7 */ // spring 4.3 change to SpringRunner.class @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:applicationContext.mvc.xml"}) // do rollback @TransactionConfiguration(defaultRollback = true) @Transactional public class TestTemplate { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; private MockHttpSession session; @Before public void setup() { // init applicationContext this.mockMvc = webAppContextSetup(this.wac).build(); this.session = new MockHttpSession(); } @Test public void getUserMsg() throws Exception { // get using get this.mockMvc .perform((get("/user/userMsg/003")) .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andDo(print()); // print } @Test // don't rollback @Rollback(false) public void putUserMsg() throws Exception { // update using put this.mockMvc .perform((put("/user/userMsg/003")) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("userName","新名字03號") .session((MockHttpSession)getLoginSession()) .accept(MediaType.parseMediaType("application/json;charset=UTF-8")) ) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andDo(print()); // print } @Test public void delUser() throws Exception { // delete using delete this.mockMvc .perform((delete("/user/userMsg/004")) .accept(MediaType.parseMediaType("application/json;charset=UTF-8")) ) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andDo(print()); //print } @Test // don't rollback @Rollback(false) public void postUser() throws Exception{ // add using post this.mockMvc .perform((post("/user/userMsg")) .param("userName", "最新的使用者") .accept(MediaType.parseMediaType("application/json;charset=UTF-8")) ) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andDo(print()); //print } /** * 獲取登入資訊session * @return * @throws Exception */ private HttpSession getLoginSession() throws Exception{ // mock request get login session // url = /xxx/xxx/{username}/{password} MvcResult result = this.mockMvc .perform((get("/user/userMsg/loginUser/loginUser"))) .andExpect(status().isOk()) .andReturn(); return result.getRequest().getSession(); } }