root() in Rest Assured

So far we have seen how to extract the data from the XML as well as from the JSON. Let me bring code from the last JSON example.

The below example is not to showcase you pass or to fail it is just to showcase the use of the root path.

import org.junit.jupiter.api.Test;
import io.restassured.RestAssured;
import static org.hamcrest.Matchers.*;
public class AssertionExample {
	@Test
	void test1() {
		RestAssured.given().when()
			.get("https://chercher.tech/sample/api/product/read")
			.then()
			.body("records[0].id", lessThan("1000"))
			.body("records[0].name", equalTo("xyz"))
			.body("records[0].description", equalTo("abc"));
	}
}

In the above example, we have used records[0] in three places, this is basically repetitions; and we can reduce the repetition by introducing the root() method. Let's use the root() method and re-write the above example.

We will set the path in the root method(), and this method has scope only for that request.

@Test
void test1() {
	RestAssured.given().when()
		.get("https://chercher.tech/sample/api/product/read")
		.then()
		.root("records[0]") // setting the root, applicable only for this request
		.body("id", lessThan("1000"))
		.body("name", equalTo("xyz"))
		.body("description", equalTo("abc"));
}

In the same request if you want to reset the root to another path then you set that as well.

.root("records[0]") // setting the root, applicable only for this request
.body("id", lessThan("1000"))
.body("name", equalTo("xyz"))
.root("the path you wish")
.body("description", equalTo("abc"));

RootPath in rest assured

In the above example, we have seen how to use a root() method to set a path for specific requests.

But in real-life scenarios, you may have multiple tests and you might have multiple requests inside the test. In such cases using a root method will not help much. To have this kind of situation rest assured provides one variable called a rootPath.

Using the root path we can set the path we wanted. This particular rootPath will be common for all the tests that you are going to use. It is recommended to reset the rootPath post-execution of your tests in a class.

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import io.restassured.RestAssured;
import static org.hamcrest.Matchers.*;
public class AssertionExample {
	@BeforeAll
	public static void setUp() {
		RestAssured.rootPath = "records[0]";
	}
	@Test
	void test1() {
		RestAssured.given().when()
			.get("https://chercher.tech/sample/api/product/read")
			.then().body("id", lessThan("1000"))
			.body("name", equalTo("xyz"))
			.body("description", equalTo("abc"));
	}
	@AfterAll
	public static void tearDown() {
		RestAssured.rootPath = "";
	}
}
About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions