1. Introduction
This article is going to cover about tagging and filtering in JUnit 5, a feature that allows test classes and methods can be tagged. And those tags can later be used to filter test discovery and execution.
The tagging feature in JUnit 5 is very similar to the Categories feature in JUnit 4. In other words, this feature of JUnit 5 is intended to replace the Categories feature of JUnit 4. We can use the tagging feature to group and label related test classes or methods together, and we can exclude or include the tests in our build process by using those tagged labels.
2. JUnit 5 Tagging and Filtering Example
2.1. Prerequisite
- A sample Java project with JUnit 5 enabled
- Maven or Gradle installed
You can refer to Getting started with JUnit 5 to get those thing ready on your machine.
2.2. Tagging a class or a test method
In JUnit 5, to tag a class or a test method, we annotate it with @Tag annotation. Let’s see an example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
@Tag("service") public class OrderServiceTest { @Test @Tag("slow") public void placeOrderTest() { } @Test @Tag("fast") public void checkout() { } @Test @Tag("slow") public void doPayment() { } @Test @Tag("fast") public void validateOrder() { } } |
2.3. Filtering tests
We can filter the tagged tests by configuring the filters extension. Here is an example how we configure the JUnit 5 Gradle plugin in order to include all the tests tagged with “service” , “fast” and exclude the tests tagged by “slow“.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
junitPlatform { // platformVersion '1.0.0-M3' filters { engines { // include 'junit-jupiter', 'junit-vintage' // exclude 'custom-engine' } tags { include 'service', 'fast' exclude 'slow' } // includeClassNamePattern '.*Test' } // enableStandardTestTask true // reportsDir file('build/test-results/junit-platform') // this is the default logManager 'org.apache.logging.log4j.jul.LogManager' } |
And here is an example how we configure the JUnit 5 Maven surefire provider to include all the tests tagged with “service” , “slow” and exclude the tests tagged by “fast“.
3. Conclusion
In this article, we have just learned about the tagging and filtering in JUnit 5, which allow us group the tests together and plan for their executions for different purposes with the filter extension. We can see several applications of this feature such as: splitting the tests according to their execution speeds (fast, slow), splitting the tests according to environment (plain Unit tests, integration tests, etc).
The sample code can be found in the Github project or you can download it by access this link: junit5-samples.zip
Below are other related article for your references:
JUnit 5 Disable or Ignore A Test
JUnit 5 Dynamic Tests – Generate Tests at Run-time
JUnit 5 Test Suite – Aggregating Tests In Suites
JUnit 5 Parameter Resolution Example