简体   繁体   English

当JUnit 5没有assertThat()函数时,如何将Hamcrest与JUnit 5一起使用?

[英]How do I use Hamcrest with JUnit 5 when JUnit 5 doesn't have an assertThat() function?

To use Hamcrest with JUnit 4 we use an assertThat() function. 要将Hamcrest与JUnit 4一起使用,我们使用assertThat()函数。 However, JUnit 5 is no longer going to have an assertThat() function. 但是,JUnit 5不再具有assertThat()函数。 How do I use Hamcrest without an assertThat() ? 如何在没有assertThat()情况下使用Hamcrest?

You have to make sure Hamcrest is included in the classpath and then use the assertThat() function provided by Hamcrest. 您必须确保Hamcrest包含在类路径中,然后使用Hamcrest提供的assertThat()函数。 From the current JUnit 5 User Guide - Writing Tests Assertions , 从当前的JUnit 5用户指南 - 编写测试断言

JUnit Jupiter's org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4's org.junit.Assert class which accepts a Hamcrest Matcher. JUnit Jupiter的org.junit.jupiter.Assertions类不提供类似于JUnit 4的org.junit.Assert类中的assertThat()方法,该类接受Hamcrest Matcher。 Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries. 相反,鼓励开发人员使用第三方断言库提供的对匹配器的内置支持。

The following example demonstrates how to use the assertThat() support from Hamcrest in a JUnit Jupiter test. 以下示例演示如何在JUnit Jupiter测试中使用Hamcrest的assertThat()支持。 As long as the Hamcrest library has been added to the classpath, you can statically import methods such as assertThat(), is(), and equalTo() and then use them in tests like in the assertWithHamcrestMatcher() method below. 只要将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)));
    }

}

Naturally, legacy tests based on the JUnit 4 programming model can continue using org.junit.Assert#assertThat." 当然,基于JUnit 4编程模型的遗留测试可以继续使用org.junit.Assert#assertThat。“

See https://github.com/junit-team/junit5/issues/147 : 请参阅https://github.com/junit-team/junit5/issues/147

you can use both, Hamcrest and AssertJ, in JUnit5. 您可以在JUnit5中同时使用Hamcrest和AssertJ。 Both frameworks have a simple assertThat method, that you can import and use if wanted. 两个框架都有一个简单的assertThat方法,您可以根据需要导入和使用它。

Currently, we do not plan to support these frameworks within our own Assertions to avoid the dependencies. 目前,我们不打算在我们自己的断言中支持这些框架以避免依赖。 Still, one can use them very well. 不过,人们可以很好地使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM