Automated Testing for REST APIs
REST APIs and microservices are exposed to the web, so security is important. Learn about automating your testing for these crucial APIs and services.
Join the DZone community and get the full member experience.
Join For FreeIntegration testing is the phase of software testing in which individual software modules are combined and tested as a group instead of testing each class independently. This can be achieved easily by using JUnit for backend code and Selenium for UI. Both of these tests can be part of Build/CI system to view the report and fail/pass the build/CI system.
Since all of us are now writing or maintaining RESTful microservices and these services/APIs are exposed to the web and distributed over different networks, they are vulnerable to risks and security threats which affect the processes based on them. Hence, testing becomes necessary to ensure they perform correctly. To test these APIs, it's very important to automate REST API test cases instead of relying on manual testing. This tutorial focuses on the basic principles, mechanics, and few ways of testing a REST API. For simplicity, the GitHub REST API will be used here.
There are various technologies and tools available; a few of them are Apache HTTP client, rest-assured, soapUI, Postman, etc. Out of all these, I will be describing Apache HTTP client, rest-assured, and soapUI.
This kind of testing will usually run as a late step in a Continuous Integration process, consuming the REST API after it has already been deployed.
When testing a REST API, the tests should focus on:
HTTP response code
Response body - JSON, XML
HTTP headers in the response
1. Writing Test Cases With Apache HTTP Client
HttpClient provides an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations.
HTTP response code
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));
}
Response body & header
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. Writing Test Cases With rest-assured
REST-assured is a Java DSL (domain specific language) for simplifying testing of REST-based services built on top of HTTP Builder. It supports POST, GET, PUT, DELETE, OPTIONS, PATCH, and HEAD requests and can be used to validate and verify the response of these requests
HTTP response code, response body & header.
@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.
}
With rest-assured, various test scenarios can be covered in a very simple way. More details about rest-assured are available here.
3. Writing Test Cases With SoapUI
SoapUI is an open source, cross-platform testing tool. It can automate functional, regression, compliance and load testing of both SOAP and REST web services. It comes with an easy-to-use graphical interface and supports industry-leading technologies and standards to mock and stimulate the behavior of web services.
Below are the steps needed to set it up and details about each step are available here.
- Creation of soapUI test project.
- Defining endpoints.
- Test case and test suite creation.
- Addition of test steps for endpoints.
- Generating the project descriptor.
Once we are done with the above steps, create a maven project with below plugin added in the pom. The below snippet assumes that the name of the project descriptor file is project.xml.
<plugin>
<groupId>com.smartbear.soapui</groupId>
<artifactId>soapui-maven-plugin</artifactId>
<version>5.2.1</version>
<configuration>
<projectFile>${basedir}/project.xml</projectFile>
</configuration>
<executions>
<execution>
<id>soapui-test</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
If it is not available under the default Maven repo, you would need to add the following repository:
<pluginRepositories>
<pluginRepository>
<id>smartbear-sweden-plugin-repository</id>
<url>http://www.soapui.org/repository/maven2</url>
</pluginRepository>
</pluginRepositories>
Run the following Maven command to run all your tests:
mvn clean integration-test
mvn clean integration-test
Opinions expressed by DZone contributors are their own.
Comments