JUnit抛出java.lang.NoClassDefFoundError:org / hamcrest / MatcherAssert

时间:2016-01-29 08:20:10

标签: java maven exception junit hamcrest

我使用 JUnit 4.11 Hamcrest 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))

2 个答案:

答案 0 :(得分:1)

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>

答案 1 :(得分:1)

您应该使用hamcrest-library代替hamcrest-allhamcrest-all并不打算与依赖项管理器一起使用,因为它是一个包含hamcrest-corehamcrest-library的超级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>