如何在JUnit 5中使用Hamcrests contains方法?

时间:2018-10-03 11:07:40

标签: java junit4 hamcrest junit5

Screenshot of Java code in Eclipse

JUnit 5似乎不包含以下Hamcrest导入的require JAR:

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.containsInAnyOrder;

当我添加hamcrest-all-1.3.jar(请参见屏幕截图)时,它可以工作,但在运行测试时却导致了错误。

我认为编译器不喜欢Junit的核心jar和我的JAR中都有重复项。

请帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

Hamcrest 1.3应该可以与JUnit 5.1一起使用,很可能是您混淆了依赖性。如果类路径与其他依赖项冲突,则可能要使用hamcrest-corehamcrest-library

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-all</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-api</artifactId>
  <version>5.1.0</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>5.1.0</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  <version>5.1.0</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.platform</groupId>
  <artifactId>junit-platform-launcher</artifactId>
  <version>1.1.0</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.platform</groupId>
  <artifactId>junit-platform-runner</artifactId>
  <version>1.1.0</version>
  <scope>test</scope>
</dependency>