Maven - How to skip tests in Java


Sometimes unit tests seem placed there from a fellow developer that abandoned the company only to bother us when we have to quickly release a simple change.

I still remember a project that nobody wanted to touch, the code was developed by an external company.

To add 1 line of productive code I had to reverse engineering the test code that was a giant black box and required 100 (!!!) lines of change.

What to do if we want quickly skip maven tests to test-drive an 'unofficial' new feature.

Option 1: Don't build the tests

Setting this parameter Maven won't compile the tests.

-Dmaven.test.skip=true or -Dmaven.test.skip

You can add it to your maven build with:

<properties> 
    <maven.test.skip>true</maven.test.skip> 
</properties> 

or you can use it directly in the command line:

$ mvn package -Dmaven.test.skip=true

Option 2: Surefire plugin - build the tests but don't execute them

This seems to be the first solution we try when we want to skip the tests (maybe because we have to type less), but often we have errors because even in absence of execution the tests are compiled, besides this instruction requires the Surefire plugin.

mvn install -DskipTests

You can add it to your project:

<project> 
  [...] 
  <build> 
    <plugins> 
      <plugin> 
        <groupId>org.apache.maven.plugins</groupId> 
        <artifactId>maven-surefire-plugin</artifactId> 
        <version>${surefire.version}</version> 
        <configuration> 
          <skipTests>true</skipTests> 
        </configuration> 
      </plugin> 
    </plugins> 
  </build> 
</project> 

Surefire plugin: skip compiling the tests

This is equivalent to the first solution, the tests are not build or executed.

mvn install -Dmaven.test.skip=true

Deep dive

Surefire gives you a lot of control in the management of the tests. You can run only one test or exclude some test according to a pattern.

If you are implementing a testing strategy for your Java project it's worth to look at the Surefire examples: https://maven.apache.org/surefire/maven-surefire-plugin/



Super fast WebApp built by Marco using SpringBoot 3 and Java 17 hosted by Infomaniak in Switzerland