乐者为王

Do one thing, and do it well.

Eclipse中Ant执行JUnit测试的问题(2)

Eclipse 3.0.3 + Ant 1.6.2 + JUnit 3.8.1

构建配置文件build.xml:

1
2
3
4
5
6
7
8
<target name="junit">
    <junit>
        <formatter type="xml" />
        <batchtest todir="${report.dir}">
            <fileset dir="${classes.dir}" includes="**/*Test.class" />
        </batchtest>
    </junit>
</target>

执行任务的时候出现了异常:

1
2
3
4
5
6
7
8
9
10
java.lang.ClassNotFoundException: com.example.learning.HelloTest
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)

网上搜索没有找到答案,到Ant官网上发现 http://ant.apache.org/faq.html#delegating-classloader 这篇文章讲了该问题。只要在junit任务里加入classpath指出要加载类的路径就可以了。修改后的build.xml文件如下:

1
2
3
4
5
6
7
8
9
10
11
<target name="junit">
    <junit>
        <classpath>
            <pathelement location="${classes.dir}" />
        </classpath>
        <formatter type="xml" />
        <batchtest todir="${report.dir}">
            <fileset dir="${classes.dir}" includes="**/*Test.class" />
        </batchtest>
    </junit>
</target>

Comments