sormuras.github.io

JUnit 5.3 Dynamic Tests with URI TestSource

Supplying a test source URI to a dynamic test enables IDEs to jump right to the underlying file the dynamic test was created for (And not to the TestFactory-annotated method as before.

2018-09-05-junit-5.3-dynamic-test-source.gif

JumpToSource.java

class JumpToSource {

  @TestFactory
  Stream<DynamicTest> checkAllTextFiles() throws Exception {
    return Files.walk(Paths.get("demo/test/jump"), 1)
        .filter(path -> path.toString().endsWith(".txt"))
        .map(path -> dynamicTest(
                "> " + path.getFileName(),
                path.toUri(), // test source uri
                () -> checkLines(path)));
  }

  private void checkLines(Path path) throws Exception {
    var lines = Files.readAllLines(path);
    var expected = lines.get(1);
    var actual = new StringBuilder(lines.get(0)).reverse().toString();
    assertEquals(expected, actual, "Second line is not the reversed first!");
  }
}