Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TestNG @BeforeClass doesn't run from super class if it not an immediate parent

Say class inheritance is like C -> B -> A where A being the topmost super class.

  class A {
     @BeforeClass
     void setUp() {
       //some stuff
      }
    }

    class B extends A {

    }

    @Test
    class C extends B {
      //running this class DOES NOT invoke setUp() from A.
    }

I have @BeforeClass testng annotation in class A. And I only annotate class C with @Test. Now, I expect that while running class C it should execute @BeforeClass annotated method in super class A. But it is not.

But it runs when I move the @BeforeClass annotation to class B.

Any ideas?

Right now, the work around is to reannotate in class B as well.

  class A {
     @BeforeClass
     void setUp() {
       //some stuff
      }
    }

    class B extends A {
      @BeforeClass
      void setUp() {
        super.setUp();
        //some stuff
      }
    }

    @Test
    class C extends B {
      //running this class invokes setUp() from only B.
    }

Note: The issue is not there if there is only two levels of inheritance to start with.

like image 824
Prabakar K Avatar asked Dec 28 '25 18:12

Prabakar K


2 Answers

The problem is you have the same method name between A and B.

When TestNG is looking for configuration methods, it won't find the annotation on the setUp() method of B. In every case, you'll have to annotate your method in B because TestNG is not able to find configuration methods without annotation.

You can keep the work around you use, or you can rename one configuration method. setUp is no more mandatory.

But we can suppose it is an issue which can be solved by TestNG too. So, you should open a ticket on the project: http://github.com/cbeust/testng

like image 181
juherr Avatar answered Dec 30 '25 07:12

juherr


When using groups for your tests you can sometimes get this behaviour as well. In that case one thing you can do to make sure the parent setup method is annotated to use alswaysRun = true, like so:

  @BeforeClass(alwaysRun = true)
  public void parentSetupClass() {

  }

Source https://testng.org/doc/documentation-main.html

For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to. For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped.

like image 23
gyosifov Avatar answered Dec 30 '25 07:12

gyosifov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!