現在我們來利用Spring Boot來構建一個RestFul API,具體如下:
1.添加Springboot測試注解
1
2
3
4
|
2.偽造mvc環境
1
2
3
4
5
6
7
8
9
|
// 注入Spring 工廠 @Autowired private WebApplicationContext wac; //偽造mvc環境 private MockMvc mockMvc; @Before public void setup(){ mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } |
3.引入靜態方法
1
2
3
4
5
6
|
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.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
3.編寫測試方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Test public void whenXXXXSuccess() throws Exception { //模擬發送請求 String result = mockMvc.perform(get( "/user" ) //發往/user的get請求,可以換成post,put,delete方法執行相應請求 .param( "username" , "xxx" ) //get請求時填寫參數的位置 .contentType(MediaType.APPLICATION_JSON_UTF8) //utf編碼 .content(content)) //post和put請求填寫參數的位置 .andExpect(status().isOk()) .andExpect(jsonPath( "$.length()" ).value( 3 )) //期望的json返回結果 .andReturn().getResponse().getContentAsString(); //對返回字符串的json內容進行判斷 log.info(result); } |
這里是具體的jsonpath語法
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/f244e2f87688