How to exclude Junit tests using Gradle or Maven in Java Applications

Introduction

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.

Prerequisites

Junit 5, Maven Surefire Plugin, Java at least 8, Gradle 5.6/6.4.1/6.5.1 or Maven 3.6.1/3.6.3

Maven Configuration

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

<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-surefire-plugin</artifactId>
			<version>3.0.0-M9</version>
			<configuration>
				<excludes>
					<exclude>**/itest/*.java</exclude>
				</excludes>
			</configuration>
			<dependencies>
				<dependency>
					<groupId>org.junit.jupiter</groupId>
					<artifactId>junit-jupiter-engine</artifactId>
					<version>5.6.2</version>
				</dependency>
			</dependencies>
		</plugin>
	</plugins>
</build>

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 com.roytuts.itest.Itest.java, then you can configure as below:

<exclude>com/roytuts/itest/Itest.java</exclude>

Or

<exclude>**/itest/Itest.java</exclude>

Gradle Configuration

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.

Thanks for reading.

Leave a Comment