0 votes
in Apache by
How can we Running JUnit Tests via Apache Ant?

1 Answer

0 votes
by

Ant allows to run JUnit tests. Ant defines junit task. You only need to include the junit.jar and the compiled classes into the classpath for Ant and then you can run JUnit tests. 

The following is a JUnit test for the previous example.

package test;

import math.MyMath;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyMathTest {
    @Test
    public void testMulti() {
        MyMath math = new MyMath();
        assertEquals(50, math.multi(5, 10));
    }
}

You can run this JUnit unit test via the following build.xml. This example assumes that the JUnit jar "junit.jar" is in folder "lib".

<?xml version="1.0"?>
<project name="Ant-Test" default="main" basedir=".">
    <!-- Sets variables which can later be used. -->
    <!-- The value of a property is accessed via ${} -->
    <property name="src.dir" location="src" />

    <property name="build.dir" location="bin" />

    <!-- Variables used for JUnit testin -->
    <property name="test.dir" location="src" />
    <property name="test.report.dir" location="testreport" />

    <!-- Define the classpath which includes the junit.jar and the classes after compiling-->
    <path id="junit.class.path">
        <pathelement location="lib/junit.jar" />
        <pathelement location="${build.dir}" />
    </path>


    <!-- Deletes the existing build, docs and dist directory-->
    <target name="clean">
        <delete dir="${build.dir}" />
        <delete dir="${test.report.dir}" />
    </target>

    <!-- Creates the  build, docs and dist directory-->
    <target name="makedir">
        <mkdir dir="${build.dir}" />
        <mkdir dir="${test.report.dir}" />
    </target>

    <!-- Compiles the java code (including the usage of library for JUnit -->
    <target name="compile" depends="clean, makedir">
        <javac srcdir="${src.dir}" destdir="${build.dir}">
            <classpath refid="junit.class.path" />
        </javac>

    </target>

    <!-- Run the JUnit Tests -->
    <!-- Output is XML, could also be plain-->
    <target name="junit" depends="compile">
        <junit printsummary="on" fork="true" haltonfailure="yes">
            <classpath refid="junit.class.path" />
            <formatter type="xml" />
            <batchtest todir="${test.report.dir}">
                <fileset dir="${src.dir}">
                    <include name="**/*Test*.java" />
                </fileset>
            </batchtest>
        </junit>
    </target>

    <target name="main" depends="compile, junit">
        <description>Main target</description>
    </target>

</project>

Related questions

0 votes
asked Nov 14, 2023 in Apache by GeorgeBell
0 votes
asked Nov 14, 2023 in Apache by GeorgeBell
...