【问题标题】:How do I use Hamcrest with JUnit 5 when JUnit 5 doesn't have an assertThat() function?当 JUnit 5 没有 assertThat() 函数时,如何将 Hamcrest 与 JUnit 5 一起使用?
【发布时间】:2017-09-02 23:08:03
【问题描述】:

要将 Hamcrest 与 JUnit 4 一起使用,我们使用 assertThat() 函数。但是,JUnit 5 不再具有assertThat() 函数。如何在没有 assertThat() 的情况下使用 Hamcrest?

【问题讨论】:

    标签: java junit5 hamcrest assertthat


    【解决方案1】:

    您必须确保 Hamcrest 包含在类路径中,然后使用 Hamcrest 提供的 assertThat() 函数。来自当前JUnit 5 User Guide - Writing Tests Assertions,

    JUnit Jupiter 的 org.junit.jupiter.Assertions 类不提供 assertThat() 方法类似于 JUnit 4 的 org.junit.Assert 中的方法 接受 Hamcrest Matcher 的类。相反,开发人员是 鼓励使用对匹配器的内置支持 第三方断言库。

    以下示例演示了如何使用 assertThat() 支持 在 JUnit Jupiter 测试中来自 Hamcrest。只要有 Hamcrest 库 已添加到类路径中,可以静态导入方法 例如 assertThat()、is() 和 equalTo(),然后在测试中使用它们 就像下面的 assertWithHamcrestMatcher() 方法一样。

    import static org.hamcrest.CoreMatchers.equalTo;
    import static org.hamcrest.CoreMatchers.is;
    import static org.hamcrest.MatcherAssert.assertThat;
    
    import org.junit.jupiter.api.Test;
    
    class HamcrestAssertionDemo {
    
        @Test
        void assertWithHamcrestMatcher() {
            assertThat(2 + 1, is(equalTo(3)));
        }
    
    }
    

    当然,基于 JUnit 4 编程模型的遗留测试可以 继续使用 org.junit.Assert#assertThat。”

    【讨论】:

    • 让我大吃一惊的是,assertThat 应该是执行所有断言的新方法,然后突然 JUnit 5 出现了,不知何故仍然拥有所有遗留的断言方法,但也删除了唯一的现代。他们已经致力于破坏 API,所以你会认为他们真的可以去那里并删除所有冗余的断言方法。起初我以为可能是为了方便迁移,但不,参数顺序甚至不一样。
    • JUnit 5 团队面临的选择是要么实现一个成熟的“现代”断言库,要么只提供最低限度的功能并将智能断言留给外部库。团队选择了后者。 Junit4 所做的就是引入外部依赖。在 Hamcrest 的特定版本上,后来被认为是一个错误,因为它导致许多版本冲突的问题。因此,完全没有外部部门是 JUnit 5 核心的基本规则。
    • @johanneslink 好的...但是assumeThat 呢?它不在 JUnit 5 的 Assumptions 静态方法中,也不在 Hamcrest 中。我们是否期望引入另一个库来获得假设?总的来说,JUnit 5 似乎对整个事情半途而废。不包括任何断言会比他们给我们的更好。
    • 为了给这个混乱局面增添更多笑料,JUnit 4 现在弃用 assertThat。即,唯一的现代断言方法现在已被弃用,而使用旧的断言方法则不是。大声笑!
    • @Trejkaz 口味和设计判断明显不同。
    【解决方案2】:

    见https://github.com/junit-team/junit5/issues/147:

    您可以在 JUnit5 中同时使用 Hamcrest 和 AssertJ。这两个框架都有一个简单的 assertThat 方法,您可以根据需要导入和使用。

    目前,我们不打算在我们自己的断言中支持这些框架以避免 依赖项。不过,人们可以很好地使用它们。

    【讨论】:

      猜你喜欢
      • 2017-11-09
      • 2018-10-23
      • 2019-10-10
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 2018-06-25
      相关资源
      最近更新 更多