简体   繁体   中英

@BeforeClass method execution in TestNG during inheritence

I have just started using TestNG, and I had a question in mind. If class A has a @BeforeSuite method and class B is inheriting class A like in the below example:

class A file:

class A
{
  @BeforeSuite
  public void beforeTest()
  {
    //something
  }
}

class B file:

class B extends A
{
 @Test
 public void executeTest()
 {
  //something
 }
}

So, in this scenario, the @BeforeSuite from class A will run for sure when I try and execute ClassB:executeTest() . Is there any way I could disable the @BeforeSuite method from running, without excluding the inheritance or disabling the @Test method?

You can override method like in example below. @BeforeSuite of the base class will not be executed in this case.

TestA:

import org.testng.annotations.BeforeSuite;
import org.testng.log4testng.Logger;

public class TestA {
    protected static Logger LOGGER = Logger.getLogger(TestA.class);

    @BeforeSuite
    public void beforeSuite() {
        LOGGER.warn("beforeSuite - TestA");
    }
}

TestB:

import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

public class TestB extends TestA {

    @BeforeSuite
    public void beforeSuite() {
        LOGGER.warn("beforeSuite - TestB");
    }

    @Test
    public void executeTest() {
        LOGGER.warn("executeTest - TestB");
    }
}

Run TestB and check output:

[TestA] [WARN] beforeSuite - TestB
[TestA] [WARN] executeTest - TestB

===============================================
Default Suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM