beforeClass测试方法运行两次Testng

时间:2015-08-22 16:10:34

标签: java testng

在下面的示例中,类方法运行两次。这是预期的行为吗?因为beforeClass应该在类运行的第一个方法之前运行一次。但是在我的课上它会运行两次。

package test;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

public class Sample1
{ 

 @BeforeSuite
 public void setUp()
 {
     System.out.println("This is before suite");
 }

 @BeforeTest
 public void init()
 {
     System.out.println("This is before Test");
 }

 @BeforeClass
 public void t1()
 {
     System.out.println("This is before class");
 }

 @BeforeMethod
 public void t3()
 {
     System.out.println("This is before Method");
 }


  @AfterMethod
  public void t4()
  {
     System.out.println("This is After Method");
  }

  @AfterClass
  public void t2()
  {
     System.out.println("This is After class");
  }

  @AfterTest
  public void cleanUp()
  {
     System.out.println("This is After Test");
  }

  @AfterSuite
  public void tearDown()
  {
     System.out.println("This is after suite");
  }

}

package test;

import org.testng.annotations.Test;

public class Sample2 extends Sample1 {

  @Test
  public void f() 
  {
      System.out.println("This is the testmethod1 in Sample2");
  }

  @Test
  public void tets1 () 
  {
      System.out.println("This is the testmethod2 in Sample2");
  }

}

<suite name="Suite1" verbose="1" >

  <test name="Regression1"   >
  <classes>
  <class name="test.Sample2">
  <methods>
  <include name = "f" />
  </methods>
  </class>
  </classes>
  </test>

  <test name="Regression2"   >
  <classes>
  <class name="test.Sample2">
  <methods>
  <include name = "tets1" />
  </methods>
  </class>
  </classes>
  </test>

</suite>

/* Output is below -- after and before class running twice

This is before suite
This is before Test
This is before class
This is before Method
This is the testmethod1 in Sample2
This is After Method
This is After class
This is After Test
This is before Test
This is before class
This is before Method
This is the testmethod2 in Sample2
This is After Method
This is After class
This is After Test
This is after suite

*/

1 个答案:

答案 0 :(得分:1)

您得到了这种行为,因为您的<suite> XML将两个测试方法作为独立测试运行。如果您允许单个测试运行两个方法,那么它们将在同一个类实例上运行,@BeforeClass只运行一次。