作者 | Biplab Pal
原文 | https://dzone.com/articles/automation-testing-for-rest-api
集成测试是软件测试的一个阶段,在软件测试中,单独软件模块作为一组进行组合和测试,而不是单独测试每个类。这可以通过使用用于后端代码的JUnit和用于UI的Selenium来轻松实现。这两个测试都可以作为构建/CI系统的一部分,来查看报告和构建/CI系统失败或通过。
由于我们现在都在写或维护RESTful微服务,这些服务或api都暴露在web上,还分布在不同的网络上,因此它们极易有风险和安全威胁,这些威胁会影响到基于它们的进程。因此为了确保它们正确地执行,测试变成必要。为了测试这些API,不依靠人工测试来自动化REST API测试用例是非常重要的。本文关注的是基本原则、机制和测试REST API的几种方法。为了简单起见,这里将使用GitHub REST API。
能获取的技术和工具有很多,其中包括Apache HTTP client,rest-assured,soapUI,Postman等等。我将介绍Apache HTTP client,rest-assured和soapUI。
这类测试通常会在持续集成过程中作为较晚的步骤运行,在它之后运行的REST API已经部署完毕。
当测试REST APIs时,我们要关注以下几点:
HTTP响应代码
响应主体 - JSON, XML
在响应中的HTTP头部
1
用Apache HTTP Client写测试用例
Http Client提供高效的、最新的和多功能的包,它实现了最新的HTTP标准和推荐的客户端。
HTTP响应代码
public void validStatusCode() throws IOException {
HttpUriRequest request = new HttpGet( "https://api.github.com/events" );
HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request );
Assert.assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(HttpStatus.OK));
}
响应主体和头部
public void responseBody() IOException {
String jsonMimeType = "application/json";
HttpUriRequest request = new HttpGet( "https://api.github.com/events" );
HttpResponse response = HttpClientBuilder.create().build().execute( request );
String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
Event[] events = new ObjectMapper().readValue(response.getEntity().
getContent(), Event[].class);
Assert.assertEquals( jsonMimeType, mimeType );
// more assert starments can be added here
}
@JsonIgnoreProperties(ignoreUnknown = true)// this is added since new ObjectMapper().readValue(response.getEntity().getContent(), Event[].class);
//throw will exception if don't have all properties(part of the response) present in this class
class Event {
private String type;
private long id;
private Repo repo;
// setters and getters for all properties goes here
}
@JsonIgnoreProperties(ignoreUnknown = true)
class Repo {
private long id;
private String name;
// setters and getters for all properties goes here
}
2
通过rest-assured写测试用例
REST-assured是Java DSL(领域专用语言)用于简化构建在HTTP Builder顶部基于服务的REST测试。它支持 POST,GET,PUT,DELETE,OPTIONS,PATCH和 HEAD 请求,并可以用于确认和验证这些请求的响应。
HTTP响应代码、响应主体和头部
@Test
public void getStatusWithRestAssured() {
Event[] events = RestAssured.get("https://api.github.com/events").then()
.statusCode(200).assertThat().contentType(ContentType.JSON)
.body("", CoreMatchers.notNullValue())
.extract().as(Event[].class);
// more assert statement goes here.
}
领取专属 10元无门槛券
私享最新 技术干货