Home > Java, Software > Running JUnit tests in Maven with Surefire Plugin and skipTests in default packaging

Running JUnit tests in Maven with Surefire Plugin and skipTests in default packaging

March 3rd, 2015


Further to the JUnit test we have created, it’s time to have it built into a maven build script so that the test can be run.
Once you have JUnit in your pom.xml file, maven will run tests with JUnit and all valid JUnit test classes under src/test/java directory.
However if you are using more than one test framework such as both TestNG and JUnit, you will need to explicitly specify JUnit as the test provider.

<plugins>
[...]
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <dependencies>
      <dependency>
        <groupId>org.apache.maven.surefire</groupId>
        <artifactId>surefire-junit47</artifactId>
        <version>2.18.1</version>
      </dependency>
    </dependencies>
  </plugin>
[...]
</plugins>

For the default maven packaging, you might not want to run test and the tests can be run as a separate job/task.
To address this, all you need to do is create a skipTests property in the pom.xml and have it set to false only when you need to run the tests.


    <properties> 
    	<skipTests>true</skipTests> 
    </properties>

Use skipTests in the configuration element.


<plugins>
[...]
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <dependencies>
      <dependency>
        <groupId>org.apache.maven.surefire</groupId>
        <artifactId>surefire-junit47</artifactId>
        <version>2.18.1</version>
      </dependency>
    </dependencies>
    <configuration>
      <skipTests>${skipTests}</skipTests>
    </configuration>
  </plugin>
[...]
</plugins>

To run the tests:
mvn test -DskipTests=false

 Follow me on twitter.





Java, Software

, ,

You might like the following posts too :

  • » Redis in Action by Josiah L. Carlson
  • » Redis Cookbook by Tiago Macedo, Fred Oliveira
  • » Continuous Enterprise Development in Java by Andrew Lee Rubinger, Aslak Knutsen
  • » Developer Programs
  • » Quick Guide to JUnit multiple parameter tests with Parameterized annotation
    1. March 7th, 2015 at 18:36 | #1

      I would suggest we rather run tests by default and switch them off in some extra situations, and not the other way around!

      Cheers!

    2. March 8th, 2015 at 22:50 | #2

      I do agree, but at times we can have a build job purely for compilation and another build job solely to run tests. I had to do it that way, hence this post. 🙂

    1. No trackbacks yet.