我不明白为什么我会从我的 ant build.xml 文件中得到这个异常。我检查了一下,一切都在类路径中。为什么一定要这么复杂?!
我过去在使用 Ant 时遇到过麻烦,它似乎总是与类路径有关。我使用两种方式指向 junit.jar:在 eclipse 中:window->preferences->ant->runtime->Ant Home->Add External Jars,以及在 build.xml 脚本中。这次 Ant 无法在 junit 任务中找到我的测试类。我指向这个类的方式有问题吗?
<target name="init">
<property name="sourceDir" value="src"/>
<property name="outputDir" value="build" />
<property name="junitLocation" value="C:\...\org.junit4_4.3.1\junit.jar" />
</target>
<target name="clean" depends="init">
<delete dir="${outputDir}" />
</target>
<target name="prepare" depends="clean">
<mkdir dir="${outputDir}" />
</target>
<target name="compile" depends="prepare">
<javac srcdir="${sourceDir}" destdir="${outputDir}" classpath="${junitLocation}"/>
</target>
<path id="classpath">
<pathelement location="${outputDir}" />
<pathelement location="${junitLocation}" />
</path>
<target name="testApplication" depends="compile">
<echo>Running the junit tests...</echo>
<junit fork="yes" haltonfailure="yes">
<test name="my.package.MyTest" />
<formatter type="plain" usefile="false" />
<classpath refid="classpath" />
</junit>
</target>
我总是得到:
[junit] Testsuite: my.package.MyTest
[junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0 sec
[junit] Caused an ERROR
[junit] my.package.MyTest
[junit] java.lang.ClassNotFoundException: my.package.MyTest
[junit] at java.net.URLClassLoader$1.run(Unknown Source)
[junit] at java.security.AccessController.doPrivileged(Native Method)
[junit] at java.net.URLClassLoader.findClass(Unknown Source)
[junit] at java.lang.ClassLoader.loadClass(Unknown Source)
[junit] at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
[junit] at java.lang.ClassLoader.loadClass(Unknown Source)
[junit] at java.lang.ClassLoader.loadClassInternal(Unknown Source)
[junit] at java.lang.Class.forName0(Native Method)
[junit] at java.lang.Class.forName(Unknown Source)
BUILD FAILED
显然,Ant 找到了 junit.jar 并尝试开始测试,但为什么找不到我的测试类?我指向包含已编译测试类的文件夹。所以我知道 junit 至少在 Ant 的类路径上,但 ClassNotFound 令我困惑。
也许有什么想法?非常感谢!
最佳答案
你确定你的测试类在 build
文件夹中吗?您在单独的 JVM (fork=true) 中调用 junit
,因此工作文件夹可能会在该调用期间发生变化,并且 build
是相对的,这可能会导致问题.
使用 -verbose 或 -debug 开关从命令行(而不是从 Eclipse)运行 ant 以查看正在调用的详细类路径/工作目录 junit
并将结果发回此处,如果你是仍然无法解决这个问题。
关于java - ant 的 junit 任务中的另一个 java.lang.ClassNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1215730/