一尘不染

TestNG中的BeforeClass和BeforeTest之间的区别

selenium

我们从TestNG官方文档中知道:

@BeforeClass: 带注释的方法将在调用当前类中的第一个测试方法之前运行。

@BeforeTest:带注释的方法将在运行属于<test>标签内部的类的任何测试方法之前运行。

上面的两个TestNG批注在功能上看起来都很相似。谁能解释这个独特的区别?


阅读 2427

收藏
2020-06-26

共1个答案

一尘不染

SeleniumAbstractTest.class

public abstract class SeleniumAbstractTest {

  @BeforeSuite
  public void beforeSuite() {
    System.out.println("BeforeSuite");
  }

  @BeforeTest
  public void beforeTest() {
    System.out.println("BeforeTest");
  }

  @BeforeClass
  public void beforeClass() {
    System.out.println("BeforeClass");
  }

  @BeforeMethod
  public void beforeMethod() {
    System.out.println("BeforeMethod");
  }

  @AfterMethod
  public void afterMethod() {
    System.out.println("AfterMethod");
  }

  @AfterClass
  public void afterClass() {
    System.out.println("AfterClass");
  }

  @AfterTest
  public void afterTest() {
    System.out.println("AfterTest");
  }

  @AfterSuite
  public void afterSuite() {
    System.out.println("AfterSuite");
  }

}

MyTestClass1.class

public class MyTestClass1 extends SeleniumAbstractTest {

  @Test
  public void myTestMethod1() {
    System.out.println("myTestMethod1");
  }

  @Test
  public void myTestMethod2() {
    System.out.println("myTestMethod2");
  }
}

MyTestClass2.class

public class MyTestClass2 extends SeleniumAbstractTest {

  @Test
  public void myTestMethod3() {
    System.out.println("myTestMethod3");
  }

  @Test
  public void myTestMethod4() {
    System.out.println("myTestMethod4");
  }
}

如果您具有以下测试套件…

<suite name="Suite">
  <test name="Test1" >
    <classes>
       <class name="MyTestClass2" />
    </classes>
  </test>

  <test name="Test2">
    <classes>
      <class name="MyTestClass1"/>
      <class name="MyTestClass2"/>
    </classes>
  </test>
</suite>

…那么输出[缩进以便于阅读]将是

BeforeSuite
'   BeforeTest
'   '   BeforeClass
'   '   '   BeforeMethod
'   '   '   '   myTestMethod3
'   '   '   AfterMethod
'   '   '   BeforeMethod
'   '   '   '   myTestMethod4
'   '   '   AfterMethod
'   '   AfterClass
'   AfterTest
'   BeforeTest
'   '   BeforeClass
'   '   '   BeforeMethod
'   '   '   '   myTestMethod1
'   '   '   AfterMethod
'   '   '   BeforeMethod
'   '   '   '   myTestMethod2
'   '   '   AfterMethod
'   '   AfterClass
'   '   BeforeClass
'   '   '   BeforeMethod
'   '   '   '   myTestMethod3
'   '   '   AfterMethod
'   '   '   BeforeMethod
'   '   '   '   myTestMethod4
'   '   '   AfterMethod
'   '   AfterClass
'   AfterTest
AfterSuite

希望能帮助到你 :)

2020-06-26