Making Maven 2 work with JUnit 4

The current stable version (2.2) of the maven-surefire-plugin does not support JUnit 4. So Maven, out of the box, does not work with JUnit 4. Luckily if we want to use JUnit 4 in our Maven based projects we have two choices. The first is to use JUnit4TestAdapter as illustrated in this post. The second is to use the snapshot version (2.3-SNAPSHOT) of the maven-surefire-plugin that has support for JUnit 4. In a small pet-project I am currently implementing I chose the second option and so far my experience was without any problems.

To use the 2.3-SNAPSHOT you first have to add the Maven snapshot plugin repository into your list of plugin repositories. In your pom.xml add the below XML:

<pluginRepositories>
  <pluginRepository>
    <id>apache.org</id>
    <name>Maven Plugin Snapshots</name>
    <url>http://people.apache.org/repo/m2-snapshot-repository</url>
    <releases>
      <enabled>false</enabled>
    </releases>
    <snapshots>
      <enabled>true</enabled>
    </snapshots>
  </pluginRepository>
</pluginRepositories>

You can also put this configuration into your ~/.m2/settings.xml file to enable this repository for all your projects.

Then go to the maven-surefire-plugin configuration section and change the version from 2.2 to 2.3-SNAPSHOT. For example below I have the maven-surefire-plugin configuration that I use in my pet-project:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.3-SNAPSHOT</version>
  <configuration>
    <includes>
      <include>**/*Test.java</include>
    </includes>
    <forkMode>once</forkMode>
  </configuration>
</plugin>

That’s it, you are done. When you run Maven again the new (2.3-SNAPSHOT) version will be downloaded and you can start using JUnit 4 in you project.

4 thoughts on “Making Maven 2 work with JUnit 4

  1. Surefire 2.2 does not support JUnit 4. I don’t remember exactly, but I think that JUnit 4 test cases (with the @Test annotation) are ignored in 2.2.

    BTW 2.3 is now final, so you don’t have to use a snapshot from the snapshots repository.

Comments are closed.