Test Templates

Let's learn how to use test templates in JUnit 5.

We discussed repeated tests and parameterized tests in previous chapters. Methods annotated with @RepeatedTest and @ParameterizedTest aren’t the actual executed tests, but templates for other tests. JUnit 5 has a specific annotation, org.junit.jupiter.api.TestTemplate, that makes a test method a test template.

Creating test templates

To create test templates, we need to create custom extensions that implement the TestTemplateInvocationContextProvider interface. This interface has two methods:

  • The boolean supportsTestTemplate(ExtensionContext context) method checks if the TestTemplateInvocationContextProvider can provide contexts for the current test method.
  • The Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContext(ExtensionContext context) method returns a stream of TestTemplateInvocationContext objects that represent the contexts for test executions. Each TestTemplateInvocationContext object has one execution of the test template.

The TestTemplateInvocationContext represents the context of each invocation of the test template. It has two default methods, String getDisplayName(int invocationIndex) and List<Extension> getAdditionalExtensions(). The getDisplayName method returns the display name for the invocation based on its index. The getAdditionalExtensions() method returns the list of additional extensions that should be used for this invocation.

The @FileSourceTest annotation

To demonstrate the usage of test templates, we’ll create an annotation that uses file lines as the source of parameters. Each file line is passed to each invocation of the test template. The code below shows the @FileSourceTest annotation, which is annotated with @TestTemplate.

Get hands-on with 1400+ tech skills courses.