代码之家  ›  专栏  ›  技术社区  ›  Alfergon

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

  •  2
  • Alfergon  · 技术社区  · 10 年前

    我正在使用编码测试 J单元4.11 汉姆克雷斯特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 回复  |  直到 10 年前
        1
  •  2
  •   Stefan Birkner    10 年前

    你应该使用 hamcrest-library 而不是 hamcrest-all . 汉克雷斯特全部 不应与依赖项管理器一起使用,因为它是一个包含 hamcrest-core 汉克雷斯特图书馆 。以下代码段应该有效。

    <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>
    
        2
  •  1
  •   Alfergon    10 年前

    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>