How to run test methods in specific order in JUnit4?

后端 未结 18 1838
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 04:35

I want to execute test methods which are annotated by @Test in specific order.

For example:

public class MyTest {
    @Test public void          


        
18条回答
  •  抹茶落季
    2020-11-22 05:10

    If the order is important, you should make the order yourself.

    @Test public void test1() { ... }
    @Test public void test2() { test1(); ... }
    

    In particular, you should list some or all possible order permutations to test, if necessary.

    For example,

    void test1(); 
    void test2(); 
    void test3(); 
    
    
    @Test
    public void testOrder1() { test1(); test3(); }
    
    @Test(expected = Exception.class)
    public void testOrder2() { test2(); test3(); test1(); }
    
    @Test(expected = NullPointerException.class)
    public void testOrder3() { test3(); test1(); test2(); }
    

    Or, a full test of all permutations:

    @Test
    public void testAllOrders() {
        for (Object[] sample: permute(1, 2, 3)) {
            for (Object index: sample) {
                switch (((Integer) index).intValue()) {
                    case 1: test1(); break; 
                    case 2: test2(); break; 
                    case 3: test3(); break; 
                }
            }
        }
    }
    

    Here, permute() is a simple function which iterates all possible permuations into a Collection of array.

提交回复
热议问题