13
Sep

Sharing variables between tests in TestNG – ITestContext

ITestContext
===============

ITestContext is basically used to store and share data across the tests in selenium by using TestNG framework.

eg. if we need to execute 10 different test cases with common varibale, this can be done with ITestContext as follow:

In TestNG any @Test method, we can be passed a parameter for “ITestContext” as follow:

@Test
public void test1a(ITestContext context){

}

To set context in TestNG Methods:
==================================

@Test
public void test1a(ITestContext context) {

String Customer_id = “C11012034”;
context.setAttribute(“CustID”, Customer_id);
}

To read context in TestNG Methods:
==================================

String Customer_id1 = (String) context.getAttribute(“CustID”);

Following example demonstrates how to share common variables across tests:
===========================================================================

package ITestContext.testng;

import org.testng.ITestContext;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ActualTest {
@BeforeTest
public void SetData(ITestContext context) {
String Customer_id = “123465”;
context.setAttribute(“CustID”, Customer_id);
}

@Test
public void Test1a(ITestContext context) {
String Customer_id1 = (String) context.getAttribute(“CustID”);
System.out.println(“In Test1, Value stored in context is: ” + Customer_id1);
}

@Test
public void Test2a(ITestContext context) {
String Customer_id1 = (String) context.getAttribute(“CustID”);
System.out.println(“In Test2, Value stored in context is: ” + Customer_id1);

}
}