ant的junit任务中的另一个java.lang.ClassNotFoundException

den*_*chr 8 java ant junit

我无法弄清楚为什么我从我的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>
Run Code Online (Sandbox Code Playgroud)

我总是得到:

    [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
Run Code Online (Sandbox Code Playgroud)

显然,Ant发现junit.jar并试图开始测试,但为什么不能找到我的测试类呢?我指向编译测试类的文件夹.所以我知道junit至少在Ant的类路径上,但是ClassNotFound让我很困惑.

也许有任何想法?非常感谢!

Chs*_*y76 6

您确定您的测试类在build文件夹中吗?您正在junit一个单独的JVM(fork = true)中调用,因此工作文件夹可能会在调用期间发生更改build并且相对而言可能会导致问题.

使用-verbose或-debug开关从命令行(而不是从Eclipse)运行ant,以查看junit正在调用的详细类路径/工作目录,如果仍然无法解决此问题,则将结果发布回此处.

  • 如果你确实需要将fork设置为yes,请将dir设置为"root"文件夹(例如`build`的父级).这应该工作.详细信息如下:http://ant.apache.org/manual/OptionalTask​​s/junit.html (2认同)