Careeroza
REST Assured Basics
Setup
REST Assured is a Java library for calling and testing REST APIs with a readable given / when / then style. It fits in the same Maven project and runs with TestNG.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>A First API Test
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ProductApiTest {
@Test
public void searchReturnsHeadphones() {
given()
.baseUri("https://qa.shopease.example.com")
.queryParam("q", "headphones")
.when()
.get("/api/products")
.then()
.statusCode(200)
.body("size()", greaterThan(0))
.body("[0].name", containsStringIgnoringCase("headphones"))
.time(lessThan(2000L));
}
}Example
mvn test -Dtest=ProductApiTestExample output
[INFO] Running com.shopease.api.ProductApiTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.912 s [INFO] BUILD SUCCESS
Tip
Tip: Notice the time: under one second for an API test, against 5–10 seconds for the same check through the browser. Careeroza's API testing topics go deeper; here we use REST Assured as a helper for UI tests.