SpringBootTest与MockMvc结合进行测试
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格式的字符串"))//指定参数类型
.param("id","100"))//如果是数字,也不用担心,会自动转换
.andExpect(MockMvcResultMatchers.status().is4xxClientError())
.andExpect(MockMvcResultMatchers.content().string("error"))
.andReturn();
System.out.println(result.getResponse().getStatus());
System.out.println(result.getResponse().getContentAsString());
}
}
说明:
@AutoConfigureMockMvc 使用MockMvc
@SpringBootTest(classes = MyApplication.class) 最好是加上classes 这样测试的时候测试环境自己会启动一套指定的springboot程序。
@ActiveProfiles("local") 指定运行的运行配置文件。
@Autowired private MockMvc mockMvc;自动注入mockmvc
对于测试使用的参数:如果直接使用.param(key,value),key类型的数字类型的,这里也可以用字符串传递过去,如果使用json格式则需要设置.contentType(MediaType.APPLICATION_JSON_VALUE).content("")或者是.contentType(MediaType.APPLICATION_FORM_URLENCODED).param(...)进行form格式的提交。
MockMvcResultMatchers.status()可以断言:
- isOk():200;
- isInternalServerError():500;
- is1xxInformational(): 1XX类型的返回码
- is2xxSuccessful(): 2XX类型的返回码
- is3xxRedirection(): 3XX类型的返回码
- is4xxClientError(): 4XX类型的返回码
- is5xxServerError(): 5XX类型的返回码