要使用Hamcrest和JUnit 4,我们使用assertThat()
函数。但是,JUnit 5不再具有assertThat()
函数。如何在没有assertThat()
的情况下使用Hamcrest?当JUnit 5没有assertThat()函数时,如何在JUnit 5中使用Hamcrest?
9
A
回答
12
您必须确保Hamcrest包含在classpath中,然后使用Hamcrest提供的assertThat()函数。从当前JUnit 5 User Guide - Writing Tests Assertions,
的JUnit木星的org.junit.jupiter.Assertions类不提供像在JUnit 4的org.junit.Assert 类中找到,它接受一个Hamcrest匹配器的 assertThat()方法。相反,鼓励开发者 使用由 第三方断言库提供的对匹配器的内置支持。
以下示例演示如何在JUnit Jupiter测试中使用来自Hamcrest的assertThat()支持 。只要已将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传统的测试。”
相关问题
- 1. 如何正确使用JUnit assertThat?
- 2. java.lang.NoSuchMethodError当使用JUnit测试运行5
- 3. JUnit Hamcrest断言
- 4. 如何一起使用JUnit和Hamcrest?
- 5. junit和hamcrest声明
- 6. 使用gradle从intellij升级JUnit 4到JUnit 5
- 7. Junit 5类似于codeception dataProvider?
- 8. 配置gradle使用JUnit,Mockito,Hamcrest和Espresso
- 9. 秩序都JUnit和Hamcrest
- 10. Iphone 5 Appium和jUnit - 应用程序没有元素
- 11. 不能让JUnit的工作(assertThat/hasItem)
- 12. 如何在Android上使用Hamcrest匹配器与jUnit
- 13. JUnit或Hamcrest是否有宽容断言?
- 14. 如何使用Ant执行JUnit 5 @Tag测试?
- 15. 为什么在Maven项目中使用JUnit 5时必须使用maven-surefire-plugin?
- 16. 如何在junit 5 gradle测试报告中捕获stdout/stderr?
- 17. 与completionTimeout没有使用JUnit
- 18. 在JUnit 5中,如何在所有测试之前运行代码
- 19. 如何在junit上测试失败截图5
- 20. 如何使用SD()函数在laravel 5
- 21. 当使用文件函数时,jUnit获取NullPointerException
- 22. 具有多个源组的Gradle中的JUnit 5
- 23. eclipse中的Junit在使用junit时产生NoClassDefFoundError
- 24. Junit测试函数
- 25. Android JUnit在Eclipse JUnit视图中没有输出
- 26. 如何将外部类的值传递给@Nested @Test int JUnit 5?
- 27. JUnit 5,Java 9和Gradle:如何传递--add-modules?
- 28. 当JUnit失败时,如何停止Maven?
- 29. 如何在Junit中调用数据源
- 30. 如何在Junit中使用注释 - eclipse
什么吹拂我的心灵是,'assertThat'是应该是做所有断言的新方法,然后突然出现JUnit 5,并以某种方式仍然拥有所有传统的断言方法,但也删除了唯一的现代方法,他们已经致力于破坏API, d认为他们真的可以到那里去除所有冗余的断言方法我认为这可能是为了方便迁移,但不是,参数顺序并不相同。 – Trejkaz