Using the TestInfoParameterResolver Class

Understand the use of dependency injection in JUnit 5 with the TestInfoParameterResolver.

In previous JUnit versions, the constructors and methods in the tests did not have parameters. With Jupiter, it’s possible to define the constructor and method parameters. This enables dependency injection for our tests.

Jupiter provides the interface, ParameterResolver, which helps an API resolve the constructor and method parameters at runtime.

The ParameterResolver interface has three main implementations— TestInfoParameterResolver, TestReporterParameterResolver, and RepetitionInfoParameterResolver.

The TestInfoParmeterResolver class

The TestInfoParameterResolver class provides an instance of TestInfo. The TestInfo interface is used to inject information about the current test, which includes the following:

  • Display Name
  • Class
  • Method
  • Tags

This interface can be used in different types of tests with annotations—@Test, @ParameterizedTest, @RepeatedTest, and @TestFactory.

It is also used for life cycle callback methods with annotations—@BeforeEach, @AfterEach, @BeforeAll, and @AfterAll.

In the JUnit 4 API, TestInfo is a drop-in replacement for the TestName rule from JUnit 4.

Example

The following code demonstrates the use of TestInfo as the constructor and method parameter.

Get hands-on with 1400+ tech skills courses.