2014-03-19 69 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"); 
    } 
}