gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:06:13 25 4
gpt4 key购买 nike

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

最佳答案

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

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. 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. 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.

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."

关于java - 当 JUnit 5 没有 assertThat() 函数时,如何将 Hamcrest 与 JUnit 5 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43280250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com