具有多个@Test方法的Junit测试类

Lin*_*R M 8 java junit junit4

我有一个Junit测试类,其中包含多个@Test方法,我需要按顺序运行.如果在方法中抛出异常,我想停止整个测试用例并输出错误,但所有其他测试方法都在运行.

public class{

@Test{
 //Test1 method`enter code here`
}

@Test{
 //Test2 method
}

@Test{
 //Test3 method
}

}
Run Code Online (Sandbox Code Playgroud)

如果Test1方法失败,则不要运行其他测试

注意:所有都是独立测试

Dun*_*nes 10

单元测试应设计为彼此独立运行.执行顺序无法保证.您应该重新设计测试类,以便顺序不重要.

没有进一步的信息,很难具体告诉你.但是有一个@before方法可能有所帮助,该方法在运行每个测试之前检查一些前提条件.如果您包含Assume.assumeTrue(...)方法调用,那么如果条件失败,您的测试可能被跳过?


Sim*_*ant 9

如此处所述,JUnit 4.11支持使用Annotation进行有序执行@FixMethodOrder,但其他测试是正确的,所有测试应该相互独立.

在测试结束时,您可以设置全局成功标志.该标志将在每次测试开始时进行测试.如果在一次测试结束时未设置该标志(因为它在完成之前失败),则所有其他测试也将失败.例:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ConsecutiveFail{
  private boolean success = true;

  @Test
  public void test1{
    //fist two statements in all tests
    assertTrue("other test failed first", success);
    success = false;
    //do your test
    //...

    //last statement
    success = true;
  }

  @Test
  public void test2{
    //fist two statements in all tests
    assertTrue("other test failed first", success);
    success = false;
    //do your test
    //...

    //last statement
    success = true;
  }
}
Run Code Online (Sandbox Code Playgroud)