How To Exclude Junit Tests Using Gradle Or Maven In Java Applications


Here in this tutorial I will tell you how to exclude Junit test cases from build automation in Java applications. It’s not about skipping test cases but it’s about excluding test cases for a particular package. Situations may arise when you want to exclude some Junit test cases from running in some environments (for example, uat, prod, etc.) while you are building your Java based application using gradle or maven build tool.

For example, you don’t want to run your Junit tests related to Mosquitto or Mqtt in Jenkins job though you may want to run these test cases in your local or development environment.


Junit 5.6.2 – 5.8.0-M1, Maven Surefire Plugin, Java at least 8, Gradle 5.6 – 6.8.3 or Maven 3.6.1/3.6.3/3.8.5

Exclude Tests using Maven

Use below configuration in maven surefire plugin to exclude the Java classes in a package. The below content is written into pom.xml file.


Look at the above configuration section in the plugin, I have excluded the Junit Java classes under the package that ends in itest.

If you want to exclude from multiple packages then you can add another <exclude/> tag with configuration under <excludes/> tag.

You can also exclude a particular java class by specifying a name. For example, if you want to exclude class, then you can configure as below:




Exclude Tests using Gradle

Using gradle tool also you can do the following configuration in build.gradle script file. The below configuration excludes all Java classes under the package that ends in itest.

test {
      exclude '**/itest/*.class'

You can exclude all classes from a particular package:

test {
    exclude 'com/roytuts/itest/**'

You can exclude classes having a name pattern, for example, Service:

test {
    exclude '**/*Service*'

You can configure other ways also as per your requirements.

Hope you got an idea how to exclude test cases using Maven or Gradle while you run the build process.

Leave a Reply

Your email address will not be published. Required fields are marked *