Apache Maven – Exclusions and Inclusions of unit test

In this article, we will learn and understand how categorically include or exclude specific test cases while running unit test using surefire plugin

 

1. Inclusions of unit test:

By default, surefire plugin will automatically pick all test cases with following wild-card (*) pattern

  • **/Test*.java –> Java test filename starting with “Test” under directory “src/test/java
  • **/*Test.java –> Java test filename ending with “Test” under directory “src/test/java
  • **/*TestCase.java –> Java test filename ending with “TestCase” under directory “src/test/java

If we don’t follow any of the above mentioned naming convention in our project, then specifically we can request maven to include certain java test files using surefire plugin in pom.xml (using <includes> tag of surefire plugin)

pom.xml

<project>
	[...]
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.18</version>
				<configuration>
					<includes>
						<include>SpringExample.java</include>
					</includes>
				</configuration>
			</plugin>
		</plugins>
	</build>
	[...]
</project>

In above example, Java test filename “SpringExample.java” will be included to run unit test via surefire plugin

2. Exclusions of unit tests:

As we aware, surefire plugin by default run unit test automatically. We can explicitly turn off or disable running test cases while executing maven’s package or install command

But this configuration disables all unit test cases, so to exclude running certain test cases, we can use <excludes> tag under surefire plugin

Q) Why we need this ?

Certain test cases fails while building (package/install) project which causes entire project to BUILD FAILURE, in those cases we can suppress/exclude that particular test case to execute

pom.xml

<project>
	[...]
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.18</version>
				<configuration>
					<excludes>
						<exclude>**/TestBookService.java</exclude>
						<exclude>**/SpringExampleTest.java</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
	[...]
</project>

In above example, Java test filename “TestBookService.java” & “SpringExampleTest.java” will be excluded to run unit test via surefire plugin

Note: we can use regular expression to include or exclude unit test cases with pattern-matching

Useful Eclipse IDE shortcuts :

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Apache Maven - Co-ordinates explained
Apache Maven - Skipping unit test using surefire plugin