How to Pass Data from One Test to Another in REST Assured
In REST Assured with Java, you can pass data from one test to another using several approaches. The most common approaches are TestNG ITestContext, static variables, dependency-based execution, and reusable test data classes.
For example, suppose you have two API tests:
- Test 1: Create a user using the POST API and capture the generated userId.
- Test 2: Use that userId in the GET API to retrieve the user details.
1. Using TestNG ITestContext (Recommended)
TestNG provides ITestContext to share data between test methods during the same test execution.
Test 1 - Create User API
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.ITestContext;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
public class UserTest {
@Test
public void createUser(ITestContext context) {
RestAssured.baseURI = "https://reqres.in";
Response response =
given()
.header("Content-Type", "application/json")
.body("""
{
"name": "Sumit",
"job": "QA Engineer"
}
""")
.when()
.post("/api/users")
.then()
.statusCode(201)
.extract()
.response();
int userId = response.jsonPath().getInt("id");
// Store data in TestNG context
context.setAttribute("userId", userId);
System.out.println("Created User ID: " + userId);
}
@Test(dependsOnMethods = "createUser")
public void getUser(ITestContext context) {
int userId = (int) context.getAttribute("userId");
given()
.when()
.get("/api/users/" + userId)
.then()
.statusCode(200);
}
}
How It Works
context.setAttribute()stores the value.context.getAttribute()retrieves the value.dependsOnMethodsensures the first test executes before the second test.- Both tests must execute within the same TestNG test context.
Note: The example uses a demonstration API. Its actual response and availability may vary.
2. Using Static Variables
You can also share data between test methods using static variables. Static variables can be accessed across different test classes within the same JVM.
UserData.java
public class UserData {
public static int userId;
}
UserTest.java
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
public class UserTest {
@Test
public void createUser() {
int userId = given()
.body("{\"name\":\"Sumit\",\"job\":\"QA\"}")
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.extract()
.path("id");
UserData.userId = userId;
}
@Test(dependsOnMethods = "createUser")
public void getUser() {
int id = UserData.userId;
given()
.get("https://reqres.in/api/users/" + id)
.then()
.statusCode(200);
}
}
Here, UserData.userId is accessible across different
test classes within the same JVM.
3. Using TestNG Dependency Between Different Classes
You can also pass data between test classes using ITestContext. Both classes must be included in the same TestNG test execution.
CreateUserTest.java
import org.testng.ITestContext;
import org.testng.annotations.Test;
public class CreateUserTest {
@Test
public void createUser(ITestContext context) {
int userId = 101;
context.setAttribute("userId", userId);
System.out.println("User Created: " + userId);
}
}
GetUserTest.java
import org.testng.ITestContext;
import org.testng.annotations.Test;
public class GetUserTest {
@Test
public void getUser(ITestContext context) {
int userId = (int) context.getAttribute("userId");
System.out.println("Fetching User: " + userId);
}
}
TestNG XML Configuration
Include both classes in the same TestNG <test> execution so they can access the same ITestContext.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="REST Assured Suite">
<test name="User API Tests">
<classes>
<class name="tests.CreateUserTest"/>
<class name="tests.GetUserTest"/>
</classes>
</test>
</suite>
Important: TestNG does not automatically guarantee execution order between different classes. For cross-class dependencies, use appropriate TestNG dependency configuration or a shared workflow in a single test class. Alternatively, use a dedicated context or data-sharing mechanism.
4. Using a Common Test Data Class
You can create a reusable class to store API response data, such as authentication tokens, user IDs, and other response values.
TestData.java
public class TestData {
private static String token;
private static int userId;
public static String getToken() {
return token;
}
public static void setToken(String token) {
TestData.token = token;
}
public static int getUserId() {
return userId;
}
public static void setUserId(int userId) {
TestData.userId = userId;
}
}
LoginTest.java
@Test
public void login() {
String token = given()
.body("{\"username\":\"admin\",\"password\":\"admin123\"}")
.post("/login")
.then()
.extract()
.path("token");
TestData.setToken(token);
}
GetProfileTest.java
@Test(dependsOnMethods = "login")
public void getProfile() {
given()
.header("Authorization", "Bearer " + TestData.getToken())
.get("/profile")
.then()
.statusCode(200);
}
The login test stores the authentication token in the TestData class. The profile test retrieves that token and uses it in the Authorization header.
5. Comparison of Different Approaches
| Approach | Scope | Recommended Usage |
|---|---|---|
| ITestContext | Same TestNG <test> context | Sharing test data between TestNG methods |
| Static Variables | Same JVM | Simple test frameworks |
| TestData Class | Same JVM | Reusable framework data |
| dependsOnMethods | Test execution dependency | Sequential API workflows |
| JSON / Properties File | Across executions | Persisting test data |
6. Recommended REST Assured Framework Structure
For a reusable REST Assured API automation framework, you can organize your project using the following structure:
RestAssuredFramework
|
+-- src
| +-- test
| +-- java
| |
| +-- tests
| | +-- CreateUserTest.java
| | +-- GetUserTest.java
| | +-- LoginTest.java
| |
| +-- utils
| | +-- TestData.java
| |
| +-- base
| +-- BaseTest.java
|
+-- pom.xml
+-- testng.xml
Recommended Approach
Use ITestContext for passing data between dependent
TestNG tests. For larger frameworks, use a dedicated test data
or context class with ThreadLocal when tests run in parallel.
Avoid shared static variables for parallel tests because different test executions can overwrite each other's data.
7. Real-World REST Assured API Testing Workflow
In real-world API automation, one API response is frequently used as input for another API request.
- Create User: Send a POST request and capture the user ID.
- Login: Send login credentials and capture the authentication token.
- Get User: Use the user ID to retrieve user details.
- Update User: Use the user ID to update user information.
- Delete User: Use the user ID to delete the user.
This approach helps build reusable, maintainable, and data-driven REST Assured API automation frameworks.

No comments:
Post a Comment