基于testng+springboot数据驱动为json 设计一套api
时间: 2024-01-31 17:03:50 浏览: 38
基于 TestNG 和 Spring Boot,可以设计一套基于 JSON 数据驱动的 API 测试框架。步骤如下:
1. 设计测试用例
在 JSON 文件中编写测试用例,包括测试 URL、请求方法、请求参数、请求头、预期响应状态码、预期响应结果等。
2. 编写测试代码
使用 TestNG 编写测试代码,读取 JSON 文件中的测试数据,发送 HTTP 请求并验证响应结果。
3. 设计数据驱动
在 TestNG 中,可以使用 DataProvider 注解实现数据驱动。在数据驱动方法中读取 JSON 文件中的数据,返回一个二维数组或者 Iterator 对象,作为测试方法的参数。
4. 集成 Spring Boot
使用 Spring Boot 框架,可以方便地管理测试环境、依赖注入等。在测试代码中,可以使用 Spring 的自动装配功能获取依赖对象,例如 RestTemplate、ObjectMapper 等。
5. 运行测试
使用 TestNG 运行测试,生成测试报告并输出结果。可以使用 Maven 或 Gradle 等构建工具自动化运行测试。
下面是一个示例代码:
```java
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApiTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private ObjectMapper objectMapper;
@DataProvider(name = "testData")
public Iterator<Object[]> testData() throws Exception {
InputStream inputStream = getClass().getResourceAsStream("/test.json");
List<Map<String, Object>> testData = objectMapper.readValue(inputStream, new TypeReference<List<Map<String, Object>>>() {});
return testData.stream().map(data -> new Object[] {data}).iterator();
}
@Test(dataProvider = "testData")
public void testApi(Map<String, Object> data) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(data.get("request").toString(), headers);
ResponseEntity<String> response = restTemplate.exchange(data.get("url").toString(), HttpMethod.valueOf(data.get("method").toString()), request, String.class);
Assert.assertEquals(response.getStatusCodeValue(), (int) data.get("status"));
Assert.assertEquals(response.getBody(), data.get("response"));
}
}
```
在这个例子中,测试数据保存在 test.json 文件中,使用 ObjectMapper 解析为 Map 对象。测试方法 testApi 读取 Map 对象中的测试数据,发送 HTTP 请求,并验证响应结果。使用 Spring Boot 自动装配 RestTemplate,可以方便地发送 HTTP 请求。使用 TestNG 的 DataProvider 实现数据驱动,可以重复执行测试方法,验证不同的测试数据。