JUnit throws java.lang.NoClassDefFoundError: org/hamcrest/MatcherAssert

JUnit throws java.lang.NoClassDefFoundError: org/hamcrest/MatcherAssert

我正在使用 JUnit 4.11Hamcrest 1.1 进行编码测试,配置如下:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-all</artifactId>
  <version>1.1</version>
  <scope>test</scope>
</dependency>

而当我运行他们时,出现以下异常:

java.lang.NoClassDefFoundError: org/hamcrest/MatcherAssert

一行包含:

assertThat(obj, hasProperty('id', 1L))

Junit 与 org.hamcrest:hamcrest-core:1.3:compile.

有自己的依赖关系

问题已通过将依赖项更改为:

得到修复
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-core</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-all</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>

您应该使用 hamcrest-library 而不是 hamcrest-allhamcrest-all 不能与依赖管理器一起使用,因为它是一个包含 hamcrest-corehamcrest-library 的 uber-jar。以下代码段应该有效。

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-library</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>