Hello, I want to write about TestNG ITestContext class usage. TestNG offers the ITestContext interface to store and shared that kind of objects through test execution.

I see that many people use inheritance in their automation project. That’s cool, that’s one of the most basic mechanism most of the programming language provides. We inherit some class for another class that we want to use a variable in another class. This is sometimes an authentication key created before triggering the whole test suite. Then we start getting null pointer exceptions while trying to use that variable in an upper class. Most of the time changing the variable to a static one solves the problem.

But is it the best way to handle those issues? What about when you do concurrent runs, what if the variable is changed by another method?

For that reason, we need to store that kind of variable in our test context.

TestNG’s ITestContext has two methods that you should be aware of.

  • setAttribute() to store variable
  • getAttribute() to get variable

Since ITestContext remains active for the duration of your test run, this is the perfect way to implement object sharing in your test suite.

Basic usage:

We call our token service, do some jsonpath manipulation and get the token from the response. Then save that token in a variable.

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

Now you are able to get rid of all those static elements and have a more solid design for your whole test suite.

Happy Testing!