如何使ant识别项目存储库中的junit.jar



我有一个使用JUnit进行单元测试的项目。问题是,当我尝试从Eclipse编译和运行我的项目时,一切都工作得很好,但是当我尝试用Ant编译时,我得到了大量的错误,它不能识别来自JUnit的任何函数(如test())。我将junit.jar复制到项目文件夹中,我的类路径是"。/",但它仍然不起作用。有人知道我该怎么做吗?

当您编译测试代码时,您需要确保JUnit jar在您的类路径中。您还需要所有其他依赖项,以及您之前编译的类的类路径。

说明你是这样编译你的常规代码的:

<property name="main.lib.dir"   value="???"/>
<property name="junit.jar"      value="???"/>
<target name="compile"
    description="Compile my regular code">
    <javac srcdir="${main.srcdir}"
        destdir="${main.destir}">
        <classpath path="${main.lib.dir}"/>
    </javac>

请注意,我有一个目录,其中包含我的代码所依赖的所有jar。这是${main.lib.dir}。注意,我的类被编译为${main.destdir}。还要注意,我在${junit.jar}中有一个属性指向实际的JUnit jar。我现在还不用那个。

现在来编译我的测试类:
<target name="test-compile"
    description="Compile my JUnit tests">
    <javac srcdir="${test.srcdir}"
        destdir="${test.destdir}">
        <classpath path="${main.lib.dir}"/>
        <classpath path="${main.destdir}"/>
        <classpath path="${junit.jar}"/>
    </javac>

注意,现在在我的类路径中有三个项目:

  1. 我编译的代码所依赖的jar文件。
  2. 编译非测试Java代码的目录
  3. 和JUnit jar本身。

在编译测试类之后,现在可以使用<junit>任务来运行测试:

<junit fork="true"
    includeantruntime="true">
    <formatter .../>
    <batchtest todir="${test.output.dir}"/>
    <classpath="${test.destdir}"/>
</junit>

最新更新