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

12

我有一个Junit测试类,其中包含多个@Test方法,需要按顺序运行。如果方法中抛出异常,我希望停止整个测试用例并报错,但是所有其他的测试方法都继续运行。

public class{

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

@Test{
 //Test2 method
}

@Test{
 //Test3 method
}

}
如果Test1方法失败,则不要运行其他测试。
注意:所有测试都是独立的。
5个回答

12

单元测试应该设计为彼此独立运行,执行顺序不能得到保证。你应该重新设计你的测试类,使得执行顺序不重要。

缺乏进一步信息很难给你具体建议。但也许有一个 @before 方法会有所帮助,在每个测试运行之前检查某些前置条件。如果你包括一个 Assume.assumeTrue(...) 方法调用,那么如果条件失败,你的测试就可以被跳过了。


11

此处所述,JUnit 4.11支持使用注解@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;
  }
}

3
我能用IntelliJ IDEA IDE实现你所需的功能,我正在使用社区版。
在包含测试方法的类中,前往编辑配置(Run --> Edit Configurations)。
选择测试类型为“Class”,如下图所示。

enter image description here

当您运行类测试时,它将执行类中所有已注释为@Test的方法,如下图所示。

enter image description here


2
如果你需要保留结果,并且不想因为测试失败而导致整个集合失败,那么请将所有这样的测试放在一个测试中,并通过假设进行测试。

1

这里是关于TESTNG如何指定测试运行顺序的示例:

@Test(priority = 1)
public void test1(){}

@Test(priority = 2)
public void test2(){}

@Test(priority = 3)
public void test3(){}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接