How To Automate GraphQL Using Rest Assured

In the last article, we learned about GraphQL and how it is different from Rest Services. In case you missed the article you can check it here. In this post, we will find out how to automate GraphQL using Rest Assured library

Introduction

Rest assured is a popular Java-based library used primarily to test Restful web services.GraphQL has gained popularity recently due to its ability to overcome the problem of overfetching and underfetching data.

Prerequisite:

Ensure the following prerequisites are met:

  1. JDK Configuration.
  2. IDE
  3. API Endpoint.

Before we start writing scripts to test GraphQL API, we need an endpoint, that will be used to demonstrate the use of the Rest assured library for GraphQL automation.

The endpoint URL is: “https://www.predic8.de/fruit-shop-graphql”

Setting Up The Maven Project

Let’s open the IDE and create a new maven project. After successful creation, open pom.xml and add below mentioned dependencies.

<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.4.0</version>
    <scope>test</scope>
</dependency>


<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.9.0</version>
    <scope>test</scope>
</dependency>

Let’s start with the basic example. We have a query using which we want to fetch the fruit details like its name, vendor, and category based on the provided input.

Request Body:

query{
  products(id: "7") {
    name
    price
    category {
      name
    }
    vendor {
      name
      id
    }
  }
}

We need to follow the below steps in Rest Assured:

  • Specify the base URL.
  • Convert GraphQL query into request payload using Jsonobject.
  • Specify Content-Type.
  • Send the Request to the Server
  • Get the Response back from the server
  • Print the returned Response’s Body.

How To Use Rest assured For Graphql Automation?

a) Create a class in the project and Import these static packages into the class file.

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import org.json.JSONObject;

b) Create a method that accepts the String payload and converts it into JSON using JSONObject.

private static String graphqlToJson(String payload)
{
     JSONObject json = new JSONObject();
     json.put("query",payload);
     return  json.toString();
}

c) Create a test method using Rest Assured to hit the endpoint and fetch the response from the server. Validate response body and status code.

Steps:

1)Provide BaseURI
2)Convert GraphQL query into JSON
3)Sent Post request with JSON payload
4)Validate the status line.

@Test
public void testGraphql()
{
RestAssured.baseURI="https://www.predic8.de/fruit-shop-graphql?";
String query="query{
  products(id: "7") {
    name
    price
    category {
      name
    }
    vendor {
      name
      id
    }
  }
}
"             
String jsonString=graphqlToJson(query);
		
given().contentType("application/json").body(jsonString)
.when().log().all().post()
.then().assertThat().statusLine("HTTP/1.1 200 OK");

Let’s understand the code. We have defined the base URI and assigned the query to a string variable. We have utilized the graphqlToJson method to convert the query into the string. This converted payload passed into the body along with the contentType header.

Dealing with Variable

Great! We have successfully written and executed our first GraphQL API test using Rest Assured. Suppose we want to test this API with an input variable. We don’t want to hardcode the data. In this case, we need to use variables. Let’s try to incorporate query variables in our test script.

Test GraphQL
QueryWithVariable

In the above screenshot, We can see the Query schema on the left and the input variable “id” in the right section. To achieve this Rest assured we will use the Data provider concept of TestNg. First, modify our API to accept input types and then provide input by using a Data provider method of the TestNG framework.

What is DataProvider?

Data Provider is an important feature provided by TestNg Framework to write data-driven tests which means that the same test method can be run multiple times with different sets of data. We will utilize this method to pass query variables as input and execute the same query for different groups of inputs.

@DataProvider
public Object[][] getQueryData(){
return new Object[][] {{"8"},
};
}

@Test(dataProvider="getQueryData")
public void testGraphqlwithVariable(String id)
{
RestAssured.baseURI="https://www.predic8.de/fruit-shop-graphql?";
String query="{\"query\":\"query($id:String!){\\n  products(id:$id) {\\n    name\\n    price\\n    category {\\n      name\\n    }\\n    vendor {\\n      name\\n      id\\n    }\\n  }\\n}\\n\","
+ "\"variables\":{\"id\":"+id+"}}";

given().log().all().contentType("application/json").body(query)
.when().log().all().post().then().log().all().assertThat()
.statusLine("HTTP/1.1 200 OK");
}

Now execute it and it will successfully fetch the result:

GraphQL using Rest Assured
Response

Let’s take a look at a different type of Schema. Here Instead of a query operation, we want to perform the mutation.

mutation ($id:Int!, $name:String!,$products[Int!]){
  updateCategory(id:$id, name:$name, products:$products) {
    name
    products {
      name
    }
  }
}

This mutation query updates the category of the existing product. To achieve this goal we will follow the same approach as we did for the simple query. Again, we will utilize the DataProvider method to feed the required data to the mutation query based on which existing category of fruits(product) will be updated.

@DataProvider
public Object[][] getMutationData(){
return new Object[][] {{7,"CherryRed"},
};
}

@Test(dataProvider="getMutationData")
public void TestMutationWithVariable(int id, String Name)
{
RestAssured.baseURI="https://www.predic8.de/fruit-shop-graphql?";
		
String Query="{\"query\":\"mutation ($id:Int!, $name:String!,$products:[Int!]){\\n  updateCategory(id:$id, name:$name,products: $products)  {\\n    name\\n    products {\\n      name\\n    }\\n  }\\n}\\n\",\"variables\":{\"id\":"+id+",\"name\":\""+Name+"\",\"products\":[2,7]}}";
				
given().contentType("application/json").body(Query)
.when().post().then().log().all().assertThat().statusLine("HTTP/1.1 200 OK");
}
	

We have seen that it is possible to use Rest Assured to write scripts for GraphQL Queries. We can use POJO classes just like Rest APIs to use serialization and deserialization concepts. By using Jackson’s data-bind library we can parse GraphQL data, which can be another alternative to automate GraphQL API.

For more theory related to Rest Assured please visit https://www.swtestacademy.com/rest-assured-tutorial-api-testing/.

Leave a Reply

Discover more from AutomationQaHub

Subscribe now to keep reading and get access to the full archive.

Continue reading