Make Selenium Easy

TestNG Tutorials 68 : Sharing Data Between Tests in a Suite Using ISuite & ITestContext

As a part of TestNG Tutorials, in this post we will see “How to share data or state among test in a suite?”.

We have covered below topics as of now:-

Sharing data between @Test annotated method using static variable concept

Sharing data between @Test annotated method using ITestContext

Let’s understand what actually I want to cover in this post. I will create two TestNG classes. In TestNG XML, I will create two tests and will add one TestNG class to each test. I would like to use data created in first test into second test. We will use concept of ITestContext. See example below:-

First TestNG Class:-

Second TestNG Class:-

TestNG XML ( Note here that I have created two tests) :-

Output:-

Observe output now. We were expecting output as “Amod Mahajan” but it printed “null Mahajan”. Actually scope of added variable in ITestContext is within current test. Outside of test, it will give you null.

What is solution of above problem?

Solution is again ITestContext but this time we need to store data at suite level in stead of a test level. ITestContext interface provides a method named getSuite() which returns a Suite object that was passed to the runner at start-up i.e. ISuite. Since ISuite interface extends IAttribute interface, you get setAttribute() and getAttribute() methods. So we need to get suite first and then set and get values.

Modified TestNG classes are as below:-

Modified first TestNG class:-

Modified second TestNG class:-

TestNG XML:-

Output:-

Note:-

  1. You can not pass ISuite reference directly to @Test annotated method like ITestContext. If you do so, you get a TestNG exception stating Cannot inject @Test annotated Method [generateData] with [interface org.testng.ISuite].
  2. You can store attributes at test and suite level together as required.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

2 thoughts on “TestNG Tutorials 68 : Sharing Data Between Tests in a Suite Using ISuite & ITestContext

  1. Thanks for this tutorial. Is there a possibility to pass the data between suite files? Say if I have a ‘Suite A’ running a few tests and ‘Suite B’ wants to use the data from ‘Suite A’, would it be possible?

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.