In below example, we are going to test response of API.
This is the API we are going to test:
https://reqres.in/api/users?page=2
Below are maven dependencies:
<dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.4.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.9.0</version> <scope>test</scope> </dependency> </dependencies>
Java Code:
import io.restassured.RestAssured; import io.restassured.response.Response; import org.testng.Assert; import org.testng.annotations.Test; public class ResponseBodyContainsTest { @Test public void testResponseBodyContains() { // Set the base URI RestAssured.baseURI = "https://reqres.in"; // Send GET request and capture response Response response = RestAssured .given() .when() .get("/api/users?page=2") .then() .statusCode(200) // Validate status code .extract() .response(); // Convert response body to String String responseBody = response.asString(); // Print for reference System.out.println("Response Body:\n" + responseBody); // Use contains() to validate specific strings Assert.assertTrue(responseBody.contains("George"), "Expected name not found in response"); Assert.assertTrue(responseBody.contains("email"), "Expected 'email' field not found in response"); Assert.assertTrue(responseBody.contains("janet.weaver@reqres.in") == false, "Unexpected email found in response"); } }
Important Points:
.contains()
is case-sensitive.
- You can test for presence/absence of any string that should/shouldn't be in the response.
- Prefer this method for quick validations; for structured validations, use JSON path instead.
No comments:
Post a Comment