Search code examples
javaseleniumselenium-webdrivertestng-eclipse

@Test is calling Parent class constructor in TestNG Selenium


I am a newbie to Java , please have a look at the below Code

//Parent Class 
public class Abc {
    Abc(){System.out.println("hiii");
    }
}

//Child Class

public class CDE extends Abc{
    @Test
    public void Xyz(){
        System.out.println("hi");
    }
    }   

Output is coming as 
hiii
hi
PASSED: Xyz

Please help , i am not sure why the constructor of parent class is getting called when i am not even using the new Keyword to create object.I have created two different classes in Eclipse.Same is not happening if i am creating main method in child class ie not using TestNG @Test annotation.


Solution

  • When you use a @Test annotation from TestNG, here's what TestNG does, behind the scenes.

    • It first loads your class.
    • It makes a list of all TestNG annotated methods that are to be run (For e.g., @Test, @BeforeClass etc.,) and orders them in the TestNG way (i.e., @BeforeSuite, @BeforeTest, @BeforeClass, @Test and so on)
    • It finds a default constructor in your class. If no default constructor is found, it tries to look for a 1 argument constructor that takes a string.
    • Using reflection the class is now instantiated.
    • Now using the instance of your test class obtained via reflection, TestNG starts calling the various annotated methods in a pre-defined order.

    The reason why your base class constructor is being invoked, is due to TestNG instantiating your child class via reflection, which triggers the constructor chain up the inheritance ladder (Which is what is called Constructor Chaining)

    You can test this theory by adding a constructor to your child class CDE and adding a System.out.println. You will see the print statement being executed.

    When you do this via a main() method, there's no reflection involved, because TestNG is not involved.