2010-11-30 12 views
29

我試圖使用@BeforeTest獲取代碼...在每次測試之前運行一次。TestNg的基礎類@BeforeTest只發生一次每夾具

這是我的代碼:

public class TestBase { 
    @BeforeTest 
    public void before() { 
     System.out.println("BeforeTest"); 
    } 
} 

public class TestClass extends TestBase{ 
    @Test 
    public void test1(){} 

    @Test 
    public void test2(){} 
} 

「BeforeTest」 只能打印一次,不是兩次。我究竟做錯了什麼?

回答

41

使用@BeforeMethod而不是@BeforeTest。

@BeforeTest的含義在the documentation中有解釋。

3

「BeforeTest」只打印一次,而不打印兩次。我究竟做錯了什麼?

***對不起。我沒有注意到你寫的是@BeforeTest,但是在你的示例中@BeforeTest幾乎等於@BeforeClass,並且更好地使用@BeforeClass,當你沒有測試類時。

@BeforeClass」應該在你的測試方法,而不是不同!

//Example 

package test; 
import org.testng.annotations.BeforeClass; 
import org.testng.annotations.BeforeMethod; 
import org.testng.annotations.Test; 

public class Tests { 
private String bClass; 
private String bMethod1; 
private String bMethod2; 

@BeforeClass 
public void beforeClass() { 
    bClass = "BeforeClass was executed once for this class"; 
} 

@BeforeMethod 
public void beforeMetodTest1() { 
    bMethod1 = "It's before method for test1"; 
} 

@Test 
public void test1() { 
    System.out.println(bClass); 
    System.out.println(bMethod1); 
} 

@BeforeMethod 
public void beforeMethodTest2() { 
    bMethod2 = "It's before method for test2"; 
} 

@Test 
public void test2() { 
    System.out.println(bClass); 
    System.out.println(bMethod2); 
} 
} 

@BeforeClass將在這個類中執行一次,在你所有的測試方法同一個類中聲明。@BeforeMethod將之前的測試方法執行,在此之前寫它

@BeforeClass可能只是一個在測試類,差異@BeforeMethod!(如果它是一些@BeforeClass,它們輪流執行,但它不是一個正確的組成測試)

P.S.對不起,我的英文:)

2

根據documentation,用@BeforeTest註解的方法在屬於標籤內部類的任何@Test方法運行之前運行。

從我的經驗:

  • 每個@BeforeTest方法只運行一次
  • 如果你有幾個@BeforeTest方法,其執行的順序取決於類的包含這些@BeforeTest方法的順序。

你可以通過設置一個簡單的例子來測試。