2014-03-19 108 views
0

在junit中,每個測試都應該獨立運行。對於更復雜的程序,你通常運行設置方法。但是我需要像每個參數之前運行的setup方法。每個參數的Junit參數化測試

可以說我有這樣的測試用例:

setup() 
contructor() 
test1() 
test2() 
test3() 
teardown() 

從執行我的JUnit的參數化測試,這將落得像這樣用2個PARAMS:

setUpBeforeClass 
contrcutor called 
test1 running 
contrcutor called 
test2 running 
contrcutor called 
test3 running 
contrcutor called 
test1 running 
contrcutor called 
test2 running 
contrcutor called 
test3 running 
tearDownAfterClass 

我需要的是一種叫做在每個參數之前。所以結果會是這樣的(改變方法與「()」):

setUpBeforeClass 
contrcutor called 
setupParam() 
test1 running 
contrcutor called 
test2 running 
contrcutor called 
test3 running 
contrcutor called 
tearDownParam() 
setupParam() 
test1 running 
contrcutor called 
test2 running 
contrcutor called 
test3 running 
tearDownParam() 
tearDownAfterClass 

我知道JUnit測試應該是原子,但每PARAM設置,過程是非常昂貴的。有沒有辦法實現這種執行順序?

在此先感謝!

更新:

@Before作爲第一個答案只會導致通話每測試之前。 例子:

setUpBeforeClass 
contrcutor called 
before 
test1 running 
contrcutor called 
before 
test2 running 
contrcutor called 
before 
test3 running 
contrcutor called 
before 
test1 running 
contrcutor called 
before 
test2 running 
contrcutor called 
before 
test3 running 
tearDownAfterClass 

回答

1

如果你想使用每個參數以上的運行對象使用@Before註解

@Before 
public void before() { 
    System.out.println("Before every test "); 
} 
+0

@Before只會導致在每次測試之前執行before()方法。我想在每個參數前執行一次。 – whereismydipp

+0

我更新了問題。你可以看到結果和我的意思。 – whereismydipp

0

,這意味着你必須參考保持它們在靜字段,因爲每個測試方法都在不同的對象上運行。

您還可以在靜態字段中保留其中一個參數的前一個值,並假設它在參數集中具有唯一值,則可以將其用作參數更改的檢測器。

這幾乎是你想要的,tearDownParams()在第一次測試新參數的構造函數後運行的小毛刺。

@RunWith(Parameterized.class) 
public class SomeTest { 

    @Parameters 
    public static Collection<Object[]> data() { 
     return Arrays.asList(new Object[][] { 
      { 1, 4, 3 }, 
      { 2, 5, 6 }, 
      { 3, 8, 12 } 
     }); 
    } 

    static int lastP1Value = -1; 

    private int p1; 

    public SomeTest(int p1, int p2, int p3) { 
     System.out.println("constructor"); 
     this.p1 = p1; 
    } 

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

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

    @Before 
    public void setUp() { 
     if (lastP1Value != p1) { 
      if (lastP1Value != -1) { 
       // this is a bit too late (after constructor for new params...) 
       tearDownParams(); 
      } 
      setUpParams(); 
     } 
     lastP1Value = p1; 
    } 

    public static void setUpParams() { 
      System.out.println(" setUpParams"); 

    } 

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