maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.1.4.RELEASE</version>
<scope>test</scope>
</dependency>
测试程序
模拟请求过程,设置期望结果:不符合结果的报错、失败,说明接口还有问题
import java.util.HashMap;
import java.util.Map;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SmartshopApplication.class)
@AutoConfigureMockMvc
public class SmartshopApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void testMockUsage() throws Exception {
ObjectMapper jsonMapper = new ObjectMapper();
// 获取请求体
Map<String, String> requestBody = new HashMap<>();
requestBody.put("mobile", "13100001111");
requestBody.put("password", "123456");
String requestBodyStr = jsonMapper.writeValueAsString(requestBody);
// 获取响应体
Map<String, String> responseBody = new HashMap<>();
responseBody.put("result_desc", "登录成功");
String responseBodyStr = jsonMapper.writeValueAsString(responseBody);
// 模拟请求过程,设置期望结果:不符合结果的报错、失败,说明接口还有问题
String returnContent = mockMvc.perform(MockMvcRequestBuilders.post("/api/login")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(requestBodyStr))
// 设置对返回内容的要求:成功
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().json(responseBodyStr))
// 获取返回体内容
.andReturn().getResponse().getContentAsString();
System.out.println(returnContent);
}
}
可结合gradle build,批量测试接口,生成测试报表,查看错误信息:gradle的配置与使用