We show how to develop a regular expression driven by automated tests in JUnit 5. Download setup from github.com/JohannesFKnauf/regex-tdd-parameterized-junit5-example and start playing.
Regex Testing: Now for JUnit 5
It’s been a year since the article series about
In the meantime, the popularity of JUnit 5 has grown. It’s time to provide sample code.
Indeed, JUnit 5 will make parameterized tests a first-class citizen. It is a new native feature. However, the JUnit 5 User Guide still marks parameterized tests as experimental.
Providing data by @MethodSource
In order to implement the exact same pattern of 1 self-sufficient simple test class, we choose the
@MethodSource test data source over more complex alternatives. I recommend to read the JUnit 5 User Guide, Nicolai Parlog’s article or Ali Dehghani’s article on Baeldung, if you want to learn more.
@MethodSource works by reading a
Arguments’ from a static method result. The second annotation we need is
@ParameterizedTest, which replaces
@Test on a method.
That’s all. Pretty simple, isn’t it? It stays ugly Java code, of course.
Of course, we still need to set up the proper dependencies.
A few notes:
org.junit.jupiter:junit-jupiter-params is the only difference to an ordinary JUnit 5 project. This artifact contains the parameterized test features.
- Pinning the surefire plugin to a recent version will already be familiar to you as a JUnit 5 user.
- Selecting Java 8 (or above) is needed to use the
Arguments.of(...) static interface methods.
Run and confirm: It’s green.
Post header background image