Configure Ant to use JUnit 4

2019-02-19 11:36发布

问题:

I googled for this, but I couldn't find any help.

I have a simple JUnit test class. Eclipse provides me with two options to run the test class in Run as JUnit Test in the Run configuration window, I see Test Runner JUnit 3 or JUnit 4. This is working fine. My classes need to use JUnit4 runner.

Now I am trying to run this from the Ant JUnit task. However, it seems to me that Ant is using JUnit3 by default. I am not sure how to set it up to use JUnit4 test runner. I have only JUnit4 jar file in the classpath and I copied ant-junit4.jar from ant lib folder to my classpath. That shows [junit] Could not find the main class: org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner. Program will exit. error.

I also tried JUnit4 Ant task. It shows there is no Junit4 ant task. Help?

Edit:

I just left the ant-junit4.jar in the ant/lib folder and just removed incudeantruntime attribute in the junit task. It works, but again it uses Junit3.

Edit

I tried running from command like following:

 `java -classpath <myclasspath that has JUnit.jar as well> org.junit.runner.JUnitCore com.my.TestClass`

and it works fine. How do I force ant Junit task to use this class org.junit.runner.JUnitCore?

回答1:

You have to make sure that you've got JUnit 4 inside of Ant lib folder. Please take a look at this question: Running "pure" JUnit 4 tests using ant



回答2:

For others help,

Ant is using Junit3 test runner by default. No way I can specify the test runner in ant Junit task. I used workaround like from this post.

Thanks @AlexanderMiles



回答3:

From Ant manual for junit task-> http://ant.apache.org/manual/Tasks/junit.html

The <junit> task supports a nested <classpath> element that represents a PATH like structure.

As of Ant 1.7, this classpath may be used to refer to junit.jar as well as your tests and the tested code.

This is where I would point to the right version of junit.jar file.

Use of dependency manager tool, such as Ivy or Maven (yes, you can use Maven just for dependencies) would be helpful here, so you don't have to commit the right version of binary junit jar file to your codebase.