2011-05-19 139 views
1

我在測試用例中有兩種方法。我想爲我的每個測試方法使用兩種不同的@BeforeTest@BeforeMethod方法。如何在單元測試用例中編寫兩個@beforeTest方法?

我在我的單元測試類中寫了兩個@BeforeMethod方法,但是這兩種方法都是爲每個單元測試方法執行而執行的。

那麼我們如何聲明@BeforeMethod方法來針對特定的測試方法單獨執行呢?

我的單元測試類的樣子:

public class MyUnitTest{ 

    String userName = null; 
    String password = null; 

    // Method 1 
    @Parameters({"userName"}) 
    @BeforeMethod 
    public void beforeMethod1(String userName){ 
     userName = userName; 
    } 

    @Parameters({"userName"}) 
    @Test 
    public void unitTest1(String userNameTest){ 
     System.out.println("userName ="+userName); 
    } 


    // Method 2 
    @Parameters({"userName","password"}) 
    @BeforeMethod 
    public void beforeMethod2(String userName,String password){ 
     this.userName = userName; 
     this.password = password; 
    } 

    @Parameters({"userName","password"}) 
    @Test 
    public void unitTest2(String userNameTest,String passwordTest){ 
     System.out.println("userName ="+this.userName+" \t Password ="+this.password); 
    } 

} 

有沒有一種方法,使:

  1. beforeMethod1方法只執行了unitTest1()方法?
  2. beforeMethod2方法只執行unitTest2()方法?

回答

3

你有兩個選擇:

  • 你可以聲明與方法參數的@BeforeMethod,檢查方法的名稱,如果它unitTest1,調用beforeMethod1(),如果它是unitTest2 ,調用beforeMethod2()。這可能不是我的第一選擇,因爲如果你改變你的方法的名字會有點脆弱。

  • 將這些方法和它們的before方法放在單獨的類中,可能共享一個公共超類。

相關問題