Error handling in REST Assured tests is important for ensuring that your API behaves as expected under various conditions. Here are some strategies to consider:
1. HTTP Status Code Validation: Always validate the HTTP status codes returned by the API.
2. Response Body Validation: Validate the response body to ensure that it contains the expected data.
3. Exception Handling: Use try-catch blocks to handle exceptions that may occur during the execution of the tests.
4. Logging: Implement logging to capture detailed information about the requests and responses.
Example :
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
public static void main(String[] args) {
try {
Response response = given()
.baseUri("https://api.example.com")
.when()
.get("/endpoint")
.then()
.statusCode(200)
.body("key", equalTo("value"))
.extract()
.response();
// Additional validation
if (response.jsonPath().getString("anotherKey") == null) {
throw new AssertionError("anotherKey is missing in the response");
}
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}?