TestNG ITestContext Usage

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.

@BeforeSuite
public void BeforeSuite(ITestContext context) {
    TokenRequest token = new TokenRequest();
    authToken = token.getAuthToken(baseUserName, baseUserPassword);
    context.setAttribute("auth", authToken);
}

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.

@Test
public void subscribe_Patient(ITestContext context) {
    InvitationsRequest invReq = new InvitationsRequest(context.getAttribute("auth").toString());
    invReq.postInvitationPatient(payload, HttpStatus.SC_CREATED);
}

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!

1 thought on “TestNG ITestContext Usage”

  1. Hi,

    i am doing something very similar in my code, but context of ITestContext is not passed between the tests in the test suite.
    what am i doing wrong? Is aAny special configuration needed?

    Thanks,
    Tatiana

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.