雖然SpringMVC的測試用例我也沒有怎麼用,但是以防以後我會用到還是寫一些筆記比較好。
使用SpringMVC的測試,需要添加Spring-test MAVEN依賴如下:
Spring-test:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency>Junit4:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
直接上測試類,註釋寫得非常詳細,基本上平時用到的測試都在這裏了。認真看看就明白了~ 但是老實說,我真的非常少用。筆者所在的團隊一共差不多20人,25個工作日的事件開發一個商城APP,事件要求非常緊。通常一個mac上的paw測測接口就OK了,真的沒有這麼花事件去寫測試用例。但是事實上時間允許的前提下,還是寫一下測試用例比較好。而且在andDo(MockMvcResultHandlers.print())方法打印出來的信息真的非常全和整潔,一出問題可以馬上發現,比日誌信息還好看。所以還是建議寫一下的····
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {ApplicationConfig.class}) @WebAppConfiguration("src/main/resources") public class TestControllerIntegration { private MockMvc mockMvc; @Autowired private WebApplicationContext ctx; @Autowired MockHttpSession session; @Autowired MockHttpServletRequest request; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build(); } @Test public void testNormalController() throws Exception { //訪問/index 添加斷言 http狀態是否200 返回的視圖是否爲/index mockMvc.perform(MockMvcRequestBuilders.get("/index")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("/index")); } @Test public void testJson() throws Exception { //訪問/loginAction登錄接口,然後添加兩個參數 用戶名和密碼, andDo 打印整個請求和影響的所有信息 //返回一個result,注意我們在最後添加andReturn方法,返回一個MvcResult 在這個Result獲得一個session MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/loginAction"). param("username", "tony"). param("password", "tonypwd")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.view().name("main")) .andDo(MockMvcResultHandlers.print()).andReturn(); this.session = (MockHttpSession) result.getRequest().getSession(); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); //使用之前的session 獲得當前登錄用戶的Json HttpHeaders headers = new HttpHeaders(); headers.setContentType(new MediaType("application","json")); result = mockMvc.perform(MockMvcRequestBuilders.post("/userInfo.json") .headers(headers).session(this.session)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); System.out.println(result.getRequest().getSession().getAttribute("loginUser")); } }
看到這裏你會說andDo(MockMvcResultHandlers.print())打印出來的信息有多詳細啊··· 呵呵 我準備好了給你們看看我的控制檯(真的非常詳細):
MockHttpServletRequest:
HTTP Method = POST
Request URI = /loginAction
Parameters = {username=[tony], password=[tonypwd]}
Headers = {}
Handler:
Type = com.tony.controller.IndexController
Method = public org.springframework.web.servlet.ModelAndView com.tony.controller.IndexController.loginAction(javax.servlet.http.HttpSession,java.lang.String,java.lang.String,java.lang.String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = main
View = null
Attribute = msg
value = other message from GlobalHandlerAdvice !!!
Attribute = username
value = tony
Attribute = loginMsg
value = 登錄成功
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = /WEB-INF/views/main.jsp
Redirected URL = null
Cookies = []
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
MockHttpServletRequest:
HTTP Method = POST
Request URI = /userInfo.json
Parameters = {}
Headers = {Content-Type=[application/json]}
Handler:
Type = com.tony.controller.IndexController
Method = public com.tony.entity.User com.tony.controller.IndexController.getUserInfo(javax.servlet.http.HttpSession)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"username":"tony","userpwd":"tonypwd"}
Forwarded URL = null
Redirected URL = null
Cookies = []
User{username='tony', userpwd='tonypwd'}