JUnit 5 with Java 14 Records
Records is a new preview feature of Java 14, and it allows to significantly simplify the code. In this article, I’ll show how to use this feature in your unit tests to make them concise and readable.
I’ll start with Maven project setup. I import two modules from JUnit 5:
junit-jupiter-api containing the basic unit test API, and
junit-jupiter-params containing extensions for parameterized tests:
The records are only available as a preview feature in Java 14. So I need to add the
--enable-preview compiler argument both for source code compilation (done by
maven-compiler-plugin), and for test running (executed by
maven-surefire-plugin). I put the plugin setup in the
I also add
target configuration parameters, to make sure the compiler uses Java 14 syntax.
As a class under test, I’m going to use this simple coding problem from the dailycodingproblem.com list —a great place to develop problem-solving skills, by the way. I’ll put this class into the
I now create a class
ProblemTest within the same package, but in the
src/test/java/com/forketyfork directory. In this class, I’m going to define a Java 14 record named
TestCase. It will contain three fields: both input parameters (
array) and the
expected result value:
Now I need to define my test data. I’ll use a method called
source, returning a
TestCase records. Note that for JUnit 5, the test data methods must be static:
Now I can use this method as a data source for my test method. The test method has to be annotated with
@ParameterizedTest annotation, and also with a
@MethodSource annotation pointing to the method name:
test method is executed once for every value in a stream provided by the
source method. The
source method returns a
Stream<TestCase>, so the
test method accepts a
TestCase instance. It uses the
array fields as input values for the test execution, and the
expected field as an expected value.
When I run this test in IntelliJ IDEA, I observe the following in the test window. Another benefit of using the records is that they have a reasonable
toString implementation, so the test cases appear to be self-descriptive:
As you see, using Java 14 records really benefits the conciseness and readability of the parameterized tests in JUnit.
The source code for the article is available at GitHub.