Image by Free-Photos from Pixabay

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:

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-api</artifactId>
  <version>5.6.2</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-params</artifactId>
  <version>5.6.2</version>
  <scope>test</scope>
</dependency>

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 pluginManagement section:

<build>
  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <source>14</source>
          <target>14</target>
          <compilerArgs>
            <arg>--enable-preview</arg>
          </compilerArgs>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M4</version>
        <configuration>
          <argLine>--enable-preview</argLine>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>

I also add source and 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 src/main/java/com/forketyfork directory, com.forketyfork package:

/**
 * Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
 * <p>
 * For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
 * <p>
 * Bonus: Can you do this in one pass?
 */
public class Problem {

    public boolean check(int target, int[] array) {
        var seen = new HashSet<Integer>();
        for (int value : array) {
            if (seen.contains(target - value)) {
                return true;
            }
            seen.add(value);
        }
        return false;
    }

}

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 (target and array) and the expected result value:

public class Problem1Test {

    private static record TestCase(int target, int[] array, boolean expected) {
    }

}

Now I need to define my test data. I’ll use a method called source, returning a Stream of TestCase records. Note that for JUnit 5, the test data methods must be static:

public static Stream<TestCase> source() {
    return Stream.of(
            new TestCase(5, new int[0], false),
            new TestCase(5, new int[] {5}, false),
            new TestCase(3, new int[] {1, 4, 2}, true),
            new TestCase(3, new int[] {1, 2}, true),
            new TestCase(3, new int[] {1, 4, 5, 8, 12}, false),
            new TestCase(13, new int[] {1, 4, 5, 8, 12}, true),
            new TestCase(12, new int[] {1, 4, 5, 8, 12}, true)
    );
}

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:

@ParameterizedTest
@MethodSource("source")
public void test(TestCase testCase) {
    Assertions.assertEquals(
      testCase.expected, 
      new Problem().check(testCase.target, testCase.array)
    );
}

The 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 target and 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.