How to use Hemcrest Matcher in assert for RestAssured Response
- Dev Raj Sinha
- Jun 18, 2023
- 1 min read
To use Hamcrest Matchers in assertions for RestAssured response, you can leverage the `assertThat()` method provided by Hamcrest along with the `Matchers` class. Here's an example of how you can use Hamcrest Matchers to assert RestAssured responses:
1. Import Required Classes:
First, import the necessary classes for RestAssured and Hamcrest Matchers:
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
2. Send API Request and Get Response:
Send the API request using RestAssured and obtain the response. Make sure the response contains valid data. Here's an example of sending a GET request and receiving the response:
Response response = RestAssured.get("https://api.example.com/endpoint");
In this example, we send a GET request to retrieve the response from `https://api.example.com/endpoint`, and the response is stored in the `response` variable.
3. Use Hamcrest Matchers for Assertion:
With the response object in hand, you can use Hamcrest Matchers to perform assertions on various aspects of the response. Here's an example:
// Assert the status code
assertThat(response.getStatusCode(), equalTo(200));
// Assert the response body contains a specific value
assertThat(response.getBody().asString(), containsString("expectedValue"));
// Assert the response header has a certain value
assertThat(response.getHeader("Content-Type"), equalTo("application/json"));
In this example, we use Hamcrest Matchers to assert the status code, check if the response body contains a specific value, and verify the value of a response header. You can use various Hamcrest Matchers based on your assertion requirements, such as `equalTo()`, `containsString()`, `hasItem()`, `hasProperty()`, and many more.
By using Hamcrest Matchers in the assertions for RestAssured responses, you can write expressive and readable assertions to validate the expected behavior of your API endpoints.
Comentarios