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

时间:2009-08-01 03:05:40

标签: 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>

我总是得到:

    [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让我很困惑。

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

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:2)

您不需要将JUnit jar添加到类路径中。如果ant无法找到它,则<junit>任务将无法运行。

我建议尝试不同的方法来指定类路径,如http://ant.apache.org/manual/using.html#path中的ant doc所述;具体而言<classpath path="${srcdir}" />可能有所帮助。

如果没有,ChssPly76建议从命令行运行ant -debug是最好的选择。你会想要在命令提示符窗口中提升缓冲区,因为ant的调试器非常冗长。

相关问题