Is there a way to get the class variables into the testNG before method of super class

501 views Asked by At

I have @test methods in a class1 and @before method in super class. I wanted to get the class variable declared in class1 to be accessed in @before method.

3

There are 3 answers

0
MarioBros On

No. That is against the rules of inheritance. The super class is the parent class, and the class1 mentioned in your question is the child class.

The child class can access the attributes of the parent class , but vica - versa is not true. Here is a similar question with more explanation.

0
Gautham M On

The term "class variable" is used to denote static variables. I assume that you intended to discuss the use of "instance variables". If an instance variable is to be used in a parent class, then ideally it should be an instance variable of the parent class.

If you actually want to use a "class variable" (or static variable) of a child class in parent class then it is possible (if it has the relevant access modifier)

4
Techrookie89 On

It is possible to access both the instance variable and a class variable using reflection. Though this is not a recommended way (as stated by comments shared).

You can use the already implemented dependency injection in testng using google's guice library for the @Before and @After hooks. Sharing an example of the same :


public class Test extends BaseTest {

    String stringOne = "INTER";
    static final String stringTwo = "MISSION";

    @Test(testName = "Sample Test")
    private void reflection_test() {
        System.out.println("-----INSIDE THE SUB CLASS-----");
        System.out.println(stringOne + stringTwo);
    }

}

Now in the @Before which is present in the base class, we add ITestResult as a param to the method (You can read about testng's dependency injection here).

Now using the ITestResult parameter, we can get the test class which can then be used to get the instantiated class object, fields, method, etc using Java reflection. Check the below example :

public class BaseTest {

    @BeforeMethod(alwaysRun = true)
    public void init(ITestResult result) throws IllegalAccessException {
        Class clazz = result.getTestClass().getRealClass();
        System.out.println("-----THIS IS FROM THE PARENT CLASS-----");
        for (Field f : clazz.getDeclaredFields()) {
            System.out.println("Variable Value : " + f.get(this));
        }
        System.out.println();
    }

}

On execution of the test, we'll receive this output :

-----THIS IS FROM THE PARENT CLASS-----
Variable Value : INTER
Variable Value : MISSION

-----INSIDE THE SUB CLASS-----
INTERMISSION