How to Use Hamcrest Matchers in GET API via Rest Assured
Hamcrest is a framework for writing matcher objects, which allow 'match' rules to be defined declaratively. In Rest Assured, we use Hamcrest matchers to write expressive assertions for validating the API response.
Maven Dependencies:
<dependencies> <!-- Rest Assured --> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.3.0</version> <scope>test</scope> </dependency> <!-- Hamcrest --> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest</artifactId> <version>2.2</version> <scope>test</scope> </dependency> </dependencies>
Commonly Used Hamcrest Matchers
Matcher | Description |
---|---|
equalTo(value) | Check equality |
hasItem(value) | Check if a list contains item |
hasItems(val1, val2) | Check if list contains multiple items |
not(value) | Asserts the opposite |
containsString(str) | Check substring match |
startsWith(str) | Check if string starts with |
API to be tested:
https://reqres.in/api/users?page=2
Java Code:
import io.restassured.RestAssured; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class GetApiHamcrestExample { public static void main(String[] args) { // Set base URI RestAssured.baseURI = "https://reqres.in"; // GET Request with Hamcrest matchers for assertions given() .log().all() .when() .get("/api/users?page=2") .then() .log().all() .statusCode(200) .body("page", equalTo(2)) // validate page number .body("data.id", hasItems(7, 8, 9)) // check if certain user IDs are present .body("data.first_name", hasItem("Michael")) // check first_name list contains value .body("support.url", containsString("reqres.in")) // substring match .body("data.email[0]", startsWith("michael")); // starts with } }
Output:
Request: GET https://reqres.in/api/users?page=2 Response: 200 OK ... Assertions: page == 2 data.id contains 7, 8, 9 data.first_name contains "Michael" support.url contains "reqres.in" data.email[0] startsWith "michael"
No comments:
Post a Comment