SpringBootTest與MockMvc結(jié)合進(jìn)行測(cè)試
POM依賴:
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.8.0-beta4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<version>2.0.4.RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
代碼示例:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import xx.flower.MyApplication;
@AutoConfigureMockMvc
@SpringBootTest(classes = MyApplication.class)
@RunWith(SpringRunner.class)
@ActiveProfiles("local")
public class MockMvcSwaggerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGet() throws Exception{
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/info/details")
// .contentType(MediaType.APPLICATION_JSON_VALUE).content("JSON格式的字符串"))//指定參數(shù)類型
.param("id","100"))//如果是數(shù)字总滩,也不用擔(dān)心,會(huì)自動(dòng)轉(zhuǎn)換
.andExpect(MockMvcResultMatchers.status().is4xxClientError())
.andExpect(MockMvcResultMatchers.content().string("error"))
.andReturn();
System.out.println(result.getResponse().getStatus());
System.out.println(result.getResponse().getContentAsString());
}
}
說(shuō)明:
@AutoConfigureMockMvc 使用MockMvc
@SpringBootTest(classes = MyApplication.class) 最好是加上classes 這樣測(cè)試的時(shí)候測(cè)試環(huán)境自己會(huì)啟動(dòng)一套指定的springboot程序棠耕。
@ActiveProfiles("local") 指定運(yùn)行的運(yùn)行配置文件睛竣。
@Autowired private MockMvc mockMvc;自動(dòng)注入mockmvc
對(duì)于測(cè)試使用的參數(shù):如果直接使用.param(key,value)晰房,key類型的數(shù)字類型的,這里也可以用字符串傳遞過(guò)去射沟,如果使用json格式則需要設(shè)置.contentType(MediaType.APPLICATION_JSON_VALUE).content("")或者是.contentType(MediaType.APPLICATION_FORM_URLENCODED).param(...)進(jìn)行form格式的提交殊者。
MockMvcResultMatchers.status()可以斷言:
- isOk():200;
- isInternalServerError():500;
- is1xxInformational(): 1XX類型的返回碼
- is2xxSuccessful(): 2XX類型的返回碼
- is3xxRedirection(): 3XX類型的返回碼
- is4xxClientError(): 4XX類型的返回碼
- is5xxServerError(): 5XX類型的返回碼