pom.xml配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
@RunWith: 该注解标签是Junit提供的,用来说明此测试类的运行者,这里用了SpringRunner,它实际上继承了 SpringJUnit4ClassRunner类,而 SpringJUnit4ClassRunner这个类是一个针对Junit 运行环境的自定义扩展,用来标准化在Springboot环境下Junit4.x的测试用例
@SpringBootTest 为 springApplication创建上下文并支持SpringBoot特性
springboot 写测试restful类型的接口的测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
Logger logger = LoggerFactory.getLogger(DemoControllerTest.class);
@Before
public void setup(){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void greetingTest() throws Exception {
logger.info("start...");
mockMvc.perform(MockMvcRequestBuilders.get("/rest/hello").contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
public void getUserTest() throws Exception {
logger.info("start...");
mockMvc.perform(MockMvcRequestBuilders.get("/rest/user").contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
第二种方法:
#自动注入一个对象
@Autowired
private TestRestTemplate testRestTemplate;
GET请求测试
@Test
public void get() throws Exception {
Map<String,String> multiValueMap = new HashMap<>();
multiValueMap.put("username","Java技术栈");
ActResult result = testRestTemplate.getForObject("/test/getUser?username={username}",ActResult.class,multiValueMap);
Assert.assertEquals(result.getCode(),0);
}
POST请求测试
@Test
public void post() throws Exception {
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","Java技术栈");
ActResult result = testRestTemplate.postForObject("/test/post",multiValueMap,ActResult.class);
Assert.assertEquals(result.getCode(),0);
}
文件上传测试
@Test
public void upload() throws Exception {
Resource resource = new FileSystemResource("/home/javastack/test.jar");
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","Java技术栈");
multiValueMap.add("files",resource);
ActResult result = testRestTemplate.postForObject("/test/upload",multiValueMap,ActResult.class);
Assert.assertEquals(result.getCode(),0);
}
文件下载测试
@Test
public void download() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set("token","javastack");
HttpEntity formEntity = new HttpEntity(headers);
String[] urlVariables = new String[]{"admin"};
ResponseEntity<byte[]> response = testRestTemplate.exchange("/test/download?username={1}",HttpMethod.GET,formEntity,byte[].class,urlVariables); if (response.getStatusCode() == HttpStatus.OK) {
Files.write(response.getBody(),new File("/home/javastack/test.jar"));
}
}
参考文档:
https://blog.csdn.net/pjmike233/article/details/82688570
本次第二部分摘自: