How to pass a variable from BeforeTest to Test annotation in TestNG?


A TestNG class can have various TestNG methods such as @BeforeTest,@AfterTest, @BeforeSuite, @BeforeClass, @BeforeMethod, @test, etc. Thereare various scenarios where we need to carry forward a few variables from thesemethods to the main @Test method. Since none of these methods support return type, the best way to pass a variable is using class /instance variable rather thanlocal variable.

The scope of class/instance variable is within the entire class. As a result, whatevervalue is set up at @BeforeTest or @BeforeMethod can be utilized at @Test method.

In this article, we will see how to pass a variable from @BeforeTest to @Test annotation in TestNG.

Approach/Algorithm to solve this problem

  • Step 1 − Create a TestNG class NewTestngClass and declare a variable as employeeName.

  • Step 2 − Write the following code inside @BeforeTest

public void name() {
   employeeName = "Ashish";
   System.out.println("employeeName is: "+employeeName);
}
  • Step 3 − Write a @Test method in the class NewTestngClass and use the variable employeeName as described in the code.

  • Step 4 − Now create the testNG.xml as given below to run the TestNG classes.

  • Step 5 − Finally, run the testNG.xml or directly testNG class in IDE or compile and run it using command line.

Example

The following code for common TestNG class, NewTestngClass

src/ NewTestngClass.java

import org.testng.annotations.*;
public class NewTestngClass {
   String employeeName;
   // test case 1
   @Test()
   public void testCase1() throws InterruptedException {
      System.out.println("in test case 1 of NewTestngClass");
      String employeeFullName = employeeName + " Anand";
      System.out.println("employeeFullName is: "+employeeFullName);
   }
   @BeforeTest
   public void name() {
      employeeName = "Ashish";
      System.out.println("employeeName is: "+employeeName);
   }
}

testng.xml

This is a configuration file that is used to organize and run the TestNG test cases. It is very handy when limited tests are needed to execute rather than the full suite.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">
   <test name = "test1">
      <classes>
         <class name = "NewTestngClass"/>
      </classes>
   </test>
</suite>

Output

employeeName is: Ashish
in test case 1 of NewTestngClass
employeeFullName is: Ashish Anand
===============================================
Suite1
Total tests run: 1, Passes: 1, Failures: 0, Skips: 0
===============================================

Updated on: 12-Jan-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements