Running “pure” JUnit 4 tests using ant

2019-02-01 20:04发布

We have migrated to both JUnit 4 and ant 1.7

The tests runs fine in eclipse, but the annotations are ignored when running the tests using ant.

According to the Ant junit task documentation:

It also works with JUnit 4.0, including "pure" JUnit 4 tests using only annotations and no JUnit4TestAdapter.

But the documentation doesn't elaborate on how it should be configured.

Is there any special setting required for the junit task? Am I missing something? We have both Tests that extends TestCase (i.e. 3.8 style) and "pure" Junit 4 tests, could that be the problem?

标签: ant junit junit4
9条回答
淡お忘
2楼-- · 2019-02-01 20:59

I am using pure JUnit4 tests with Ant.

Here is the interesting part of my build file:

<junit printsummary="yes" haltonfailure="yes">
    <formatter type="xml"/>
    <classpath refid="path.test"/>
    <batchtest fork="yes" todir="${dir.report.unittests.xml}">
        <fileset dir="src">
            <include name="**/*Test*.java"/>
        </fileset>
    </batchtest>
</junit>

Make sure you have the latest version of the junit.jar file in the lib directory of Ant. As far as I know the required version is delivered with ant 1.7 or higher versions...

查看更多
别忘想泡老子
3楼-- · 2019-02-01 21:00

This happened to me and it was because I was both using annotations and extending TestCase.

public class TestXXX extends TestCase {

    @Test
    public void testSimpleValidCase() {
        // this was running
    }

    @Test
    public void simpleValidCase() {
        // this wasn't running
    }
}

When you extend TestCase you are assuming JUnit3 style so JUnit4 annotations are ignored.

The solution is to stop extending TestCase.

查看更多
叼着烟拽天下
4楼-- · 2019-02-01 21:05

I also tried to do tests with JUnit 4.0 without JUnit4TestAdapter, i.e. without method
public static junit.framework.Test suite() { return new JUnit4TestAdapter(SomeTestClass.class); }

I use ant 1.9.4. Running ant test verbose (ant -v ) shows

[junit] Running multiple tests in the same VM
[junit] Implicitly adding /usr/share/java/junit.jar:/usr/sharejava/ant-launcher.jar:/usr/share/java/ant.jar:/usr/share/java/ant/ant-junit.jar to CLASSPATH

Aha, but still there is some ant-junit-task. Downloading this shows in addition /usr/share/java/ant/ant-junit4.jar which is not added implicitly. I just added it explicitly:

<junit printsummary="yes" 
    fork="yes" 
    forkmode="once"
    maxmemory="1023m" 
    showoutput="no">
    ...
   <classpath>
     <pathelement path="...:${junitJar}:${hamcrestJar}:/usr/share/java/ant/ant-junit4.jar" />
   </classpath>
...
</junit>

and it worked. Without: no. I am aware that this solution is not beautiful at all...

查看更多
登录 后发表回答