To validate that a JSON response body contains a specific key using hasKey()
from Hamcrest Matchers in Rest Assured, follow this step-by-step guide using the endpoint:
URL: https://reqres.in/api/users?page=2
Goal: Validate that the JSON response has a key like "page"
, "data"
, etc.
Code Example in Java (Rest Assured + Hamcrest hasKey()
)
import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class HasKeyExample { public static void main(String[] args) { RestAssured.baseURI = "https://reqres.in"; given() .when() .get("/api/users?page=2") .then() .statusCode(200) .body("$", hasKey("page")) // top-level key .body("$", hasKey("per_page")) // another top-level key .body("$", hasKey("data")) // array of users .body("support", hasKey("url")) // nested key inside "support" .body("support", hasKey("text")); // another nested key } }
Explanation:
"$"
refers to the root of the JSON response.hasKey("keyName")
checks if a key exists at that JSON level.body("support", hasKey("url"))
checks if thesupport
object has aurl
key.
Sample Response from
https://reqres.in/api/users?page=2
{ "page": 2, "per_page": 6, "total": 12, "total_pages": 2, "data": [...], "support": { "url": "https://reqres.in/#support-heading", "text": "To keep ReqRes free, contributions towards server costs are appreciated!" } }
Maven Dependencies
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.3.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest</artifactId> <version>2.2</version> </dependency>
No comments:
Post a Comment