To validate a GraphQL API using Rest Assured in Java, follow these key steps:
Key Concepts
- GraphQL APIs use a single endpoint (typically
/graphql
) for all operations. - The query or mutation is passed as a JSON payload (usually in the body of a POST request).
- Response is usually in JSON, and can be validated using JsonPath, Matchers, etc.
Public GraphQL API for Example
We'll use the public GraphQL API from https://countries.trevorblades.com/
Endpoint: https://countries.trevorblades.com/
Example Query (returns name and capital of India):
{ country(code: "IN") { name capital } }
Java Code Using Rest Assured
import io.restassured.RestAssured; import io.restassured.response.Response; import org.json.JSONObject; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; public class GraphQLApiTest { public static void main(String[] args) { // GraphQL query as string String query = "{ country(code: \"IN\") { name capital } }"; // Prepare the JSON body JSONObject requestBody = new JSONObject(); requestBody.put("query", query); // Set base URI RestAssured.baseURI = "https://countries.trevorblades.com/"; // Send POST request and validate response given() .header("Content-Type", "application/json") .body(requestBody.toString()) .when() .post() .then() .statusCode(200) .body("data.country.name", equalTo("India")) .body("data.country.capital", equalTo("New Delhi")); } }
Validations Performed
HTTP status code =
200
Country name =
"India"
Capital =
"New Delhi"
Maven Dependencies:
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>5.3.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </dependency>
No comments:
Post a Comment