Junit ErrorCollector 用法 - 失败不显示

Junit ErrorCollector usage - failure does not show

我有几个断言,我想收集所有的问题,最后整个测试应该失败并有正确的控制台输出。但是现在,我什么都没有。

    @Rule
    public ErrorCollector collector = new ErrorCollector();
    Matcher<Boolean> matchesTrue = IsEqual.equalTo(true);

collector.checkThat("FAILURE","BLA".equals("OK"), matchesTrue);
collector.checkThat("FAILURE","BLABLA".equals("OK"), matchesTrue);

在 运行 之后,一切都是绿色的,控制台上没有错误。

有什么问题?

谢谢!

您的代码看起来有效。下面的测试...

public class ErrorCollectorTest {

  @Rule
  public ErrorCollector collector = new ErrorCollector();

  @Test
  public void testErrorCollection() {
    org.hamcrest.Matcher<Boolean> matchesTrue = org.hamcrest.core.IsEqual.equalTo(true);

    collector.checkThat("FAILURE", "BLA".equals("OK"), matchesTrue);
    collector.checkThat("FAILURE", "BLABLA".equals("OK"), matchesTrue);
  }
}

... 产生此输出:

java.lang.AssertionError: FAILURE
Expected: <true>
     but: was <false>

    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.junit.Assert.assertThat(Assert.java:956)
    at org.junit.rules.ErrorCollector.call(ErrorCollector.java:65)
    at org.junit.rules.ErrorCollector.checkSucceeds(ErrorCollector.java:78)
    at org.junit.rules.ErrorCollector.checkThat(ErrorCollector.java:63)
    ...


java.lang.AssertionError: FAILURE
Expected: <true>
     but: was <false>

    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.junit.Assert.assertThat(Assert.java:956)
    at org.junit.rules.ErrorCollector.call(ErrorCollector.java:65)
    at org.junit.rules.ErrorCollector.checkSucceeds(ErrorCollector.java:78)
    at org.junit.rules.ErrorCollector.checkThat(ErrorCollector.java:63)
    ...

这已通过 JUnit 4.12 和 Hamcrest 验证

如果您使用的是 Junit 5 (Jupiter),则需要以下附加依赖项才能使 @ErrorCollector 规则生效:

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-migrationsupport</artifactId>
        <version>${jupiter.version}</version>
        <scope>test</scope>
    </dependency>

之后,您需要在测试 class 级别包含 @EnableRuleMigrationSupport 注释。