【问题标题】:ant LinkageError without includeantruntimeant LinkageError without includeantruntime
【发布时间】:2015-08-29 03:28:03
【问题描述】:

如何防止 AntClassLoader 和 URLClassLoader 导致链接错误?

由于项目较旧,将 junit 和 hamcrest.core 放入 ANT_HOME 中,我们的构建使用 includeantruntime=true 来运行单元测试。

我现在正在处理一个用 ant 构建的项目,我不想依赖 ANT_HOME 中的任何 jar 文件。我虔诚地在所有 javac 节中使用了 includeantruntime=false。

但是,现在我使用 hamcrest 进行测试,我遇到了运行时链接错误。

java.lang.LinkageError: loader constraint violation: when resolving method 
"org.junit.Assert.assertThat(Ljava/lang/Object;Lorg/hamcrest/Matcher;)V" 
the class loader (instance of org/apache/tools/ant/loader/AntClassLoader5) 
of the current class, myclass, and the class loader (instance of
java/net/URLClassLoader) for resolved class, org/junit/Assert, have different
Class objects for the type assertThat used in the signature

junit 运行测试时出现运行时链接错误。

我似乎有两个选择,我都不喜欢:

  1. 从 ANT_HOME 中删除 junit 和 hamcrest.core。这打破了另一个 项目。
  2. 从项目中移除 junit 和 hamcrest.core 并依赖 ANT_HOME 中的设置。这是我想要避免的。

我原以为 includeantruntime 会有所帮助。

我的目标是让 junit 和 hamcrest.core 保留在 ANT_HOME 中,同时将它们包含在项目中。也就是说,ANT_HOME 的内容应该无关紧要。

这个问题有解决办法吗?

【问题讨论】:

    标签: java ant junit


    【解决方案1】:

    设置“includeantruntime=false”是件好事。它迫使您的构建更加独立,并且更少依赖本地机器的配置,我喜欢将这个问题称为“魔法构建服务器”(没有人真正知道它是如何工作的)

    我使用Apache ivy 来管理我的 ANT 类路径依赖项。下面给出一个在本地“lib”目录中使用 jars 的示例:

    ivy 的真正强大之处在于将它与 Maven 存储库结合使用。您的源代码仍然是可移植的,但不必随所有 3rd 方 jar 一起提供。起初它看起来令人生畏,但这是一种值得研究的方法。 Maven 做对了一些事情 :-)

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      解决这个问题有两个步骤:

      1. <pathelement path="${java.class.path}" /> 添加到测试环境的类路径中。
      2. fork="true" 添加到junit 元素的属性中。您还可以为 junit 元素选择一种 fork 模式。例如,我使用了forkmode="once"

      includeantruntime 在所有条件下都应保持为false

      Allow junit to fork 明确地将 junit 类加载器与 ant 类加载器分开,以防止任何无意的关联。需要 java.class.path 来明确允许 ant 找到所有需要执行的类。

      通过这些设置,ant lib 目录下的库不被使用,不会干扰JUnit测试。

      【讨论】:

        猜你喜欢
        • 2013-09-12
        • 2011-06-16
        • 2016-06-25
        • 1970-01-01
        • 1970-01-01
        • 2019-11-09
        • 2011-07-03
        • 2010-10-18
        • 1970-01-01
        相关资源
        最近更新 更多