【问题标题】:Why am I getting NoClassDefFound org/hamcrest/SelfDescribing if I'm not using hamcrest at all in my Maven test?如果我在 Maven 测试中根本没有使用 hamcrest,为什么会收到 NoClassDefFounderror org/hamcrest/SelfDescribeing?
【发布时间】:2020-11-20 23:03:35
【问题描述】:

我已经有一段时间了。 StackOverflow 中的相关问题是关于项目的classpath 中没有hamcrest-core JAR,解决方法都与它的添加有关。我想做的是相反的:从类路径中删除这个依赖。

考虑一个带有单个测试用例的 Maven 项目:

import static org.junit.Assert.assertTrue;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class AppTest {

    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue() {
        assertTrue(true);
    }
}

这里的测试shouldAnswerWithTrue从依赖junit版本4.11(在POM中声明)调用Assert类中的方法assertTrue。当我构造相应的调用图时,这个测试用例中似乎没有使用依赖hamcrest-core。 hamcrest-core 是由直接依赖 junit 引起的传递依赖。因此,我继续将其从我的项目的 POM 中排除如下:

<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>

但是,当我执行mvn package 时,会触发以下错误:

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

我不明白为什么 Java 在我的测试及其任何方法调用中根本没有使用的依赖项中抱怨接口 SelfDescribing。我检查了 hamcrest-core 中的任何类都没有从 JUnit 中的 Assert 类中加载。

那么,为什么我不能排除hamcrest-core?为什么需要这个接口?叫什么名字?

【问题讨论】:

  • 问题很简单。 search.maven.org/artifact/junit/junit/4.11/jar 如果您查看 junit 的 pom 文件,您会看到定义了对 hamcrest 的依赖项,这意味着它是必需的。最后,排除项目管理员决定使用的依赖项是没有意义的。所以你会得到一个 NoClassDefFoundError 并不奇怪。

标签: java maven junit dependencies hamcrest


【解决方案1】:

因为 JUnit 4.11 实际上在编译时依赖于它:它uses it in its exception hierarchy。当AssumptionViolatedException类被加载时,会触发SelfDescribing的加载。

【讨论】:

  • 我刚刚在给定的例子中执行了mvn compiler:testCompile -Dverbose=true。但是,根据输出,没有加载来自 hamcrest 的类。如何查看SelfDescribing的负载?
猜你喜欢
  • 2013-01-10
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
相关资源
最近更新 更多