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