Filter JUnit 5 tests on Gradle with command-line arguments
How to selectively run JUnit 5 tests in a gradle project using tags, command-line arguments and a few additions to a build.gradle file.
I ran into an issue I genuinely thought probably had inbuilt support, but apparently not. The JUnit platform on Gradle does have configuration support which allows filtering of tests via tags, however to use this, you have to create different tasks with different configurations applying your desired filters.
This can get repetitive as you can imagine; if you’re using a reporter like Jacoco, you’d have to duplicate the configuration in each task to output the reports. Wouldn’t it be nice if we could have one “test” task that can filter tests dynamically based on arguments passed when invoking the task? Well, you can!
When running a gradle task from the command-line, you can pass system properties using the “-D” flag, we can leverage this to pass our filters into the task. The build.gradle file is written in groovy, meaning we can use groovy code to declare variables, write conditional statements and do a host of other things. Combining these two, you can build a dynamic JUnit configuration for the “test” task and include the tags that way, so what does this look like?
With this change, we have a single configuration that can include and exclude tags dynamically based on the arguments passed when calling the task. So how do we actually call the task?
You can annotate your tests (classes &/or methods) with multiple tags at the same time and I’d recommend a static class with your “tags” to avoid magic strings and typos in your test classes. You can use a pattern similar to the one below:
That’s it! Now we can filter our tests from the command-line wherever we may need to do so, CI build systems, IDEs and all.
Thanks for reading this far! Good luck and keep coding. ✨