即使其中一个断言失败,也会在junit4中继续执行测试

use*_*r85 48 java junit4

我使用Jfunc构建了现有的框架,即使在测试用例中的一个断言失败时也提供了继续执行的工具.Jfunc使用junit 3.x框架.但是现在我们正在迁移到junit4,所以我不能再使用Jfunc并用junit 4.10 jar替换它.
现在的问题是因为我们在框架中广泛使用了jfunc,而对于junit 4,我们希望使代码继续执行,即使其中一个断言在测试用例中失败.
有没有人对此有任何建议/想法,我知道在junit中测试需要更加原子化,即每个测试用例一个断言,但由于某种原因我们不能在我们的框架中这样做.

Chr*_*s B 64

您可以使用ErrorCollector规则执行此操作.

要使用它,首先将规则添加为测试类中的字段:

public class MyTest {
    @Rule
    public ErrorCollector collector = new ErrorCollector();

    //...tests...
}
Run Code Online (Sandbox Code Playgroud)

然后用调用来替换你的断言collector.checkThat(...).

例如

@Test
public void myTest() {
    collector.checkThat("a", equalTo("b"));
    collector.checkThat(1, equalTo(2));
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回复克里斯.它在第一次失败后工作并继续(即collector.checkThat(10,CoreMatchers.equalTo(11))).但问题是我希望它将测试标记为失败,即使其中一个检查失败.目前,在执行上述测试后,测试标记为已通过.我希望它失败并在失败线上显示堆栈跟踪(类似于断言失败时的情况). (3认同)

Sta*_*Quo 19

我也使用ErrorCollector,但也使用assertThat并将它们放在try catch块中.

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

@Rule
public ErrorCollector collector = new ErrorCollector();

@Test
public void calculatedValueShouldEqualExpected() {
    try {
        assertThat(calculatedValue(), is(expected));
    } catch (Throwable t) {
        collector.addError(t);
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)


mar*_*rok 7

您还可以使用assertj - 软断言

@Test
public void testCollectErrors(){
   SoftAssertions softly = new SoftAssertions();
   softly.assertThat(true).isFalse();
   softly.assertThat(false).isTrue();
   // Don't forget to call SoftAssertions global verification !
   softly.assertAll();
}
Run Code Online (Sandbox Code Playgroud)

还存在其他使用它的方法,无需手动调用 softly.assertAll();

  1. 有规则
  2. 带自动关闭功能
  3. 使用静态的assertSoftly方法