TestNG ITestContext Usage

Development & UX Researches
1 min readFeb 4, 2021

--

I was focusing on Singleton and Factory model to keep data on the testing suite during test executions. This is a real pain to deal all will approve of this. When I learned TestNG gives the ITestContext interface to store and shared that form of an object through check execution, I tried and saw the huge usage of it. We inherit a few magnificence for some other elegance that we need to apply a variable in some other magnificence. this is occasionally an authentication key created before triggering the complete check suite. Then we begin getting null pointer exceptions at the same time as seeking to use that variable in a top elegance and most of the time converting the variable to a static one solves the hassle. TestNG’s ITestContext handles this issue very obvious and clear way and knowledge of this is the attributes we use:

setAttribute() to store variablegetAttribute() to get variable

Imagine we keep generating a UUID name and want to keep using it in the next step:

@BeforeSuite
public void BeforeSuite(ITestContext context) {
UUID uuid = new UUID();
String filename = uuid;
context.setAttribute(“fileName”, filename);
}

In general, the Test function doesn’t have input but in order to reach the ITestContext variable, we need to pass an ITestContext variable. Then use it anyway way you want it.

@Test
public void subscribe_Patient(ITestContext context) {
String path = context.getAttribute(“fileName”).toString();
File file = mew File(path);
}

Relying more than on OOP, POJO, Singleton, or Static members on upon, now we have a handier and stable layout for your whole test suite.

--

--

Development & UX Researches

A self-learner in the programming and UX industry. Keep yourself updated in this journey together ;)