November 17, 2016

JUnit 5 introduced parameters for tests. In order for the parameters to work, a ParameterResolver has to be provided. If any test method parameter can’t be resolved, the tests will not be executed at all. For example:

Will work, because TestInfo is a class provided by JUnit 5. It contains all kinds of information about the current test.

Parameter Resolver Extension Point

Writing your own ParameterResolver is pretty straight forward. You simply create a class which extends the ParameterResolver interface and use it in your tests like you would any other extension: @ExtendWith(MyParameterResolver.class) on either a class, constructor or method.

To show you how to create your own ParameterResolver, I will build on my previous post about Dynamic Tests. The original test methods looked like this:

Now we want them to be like this:

With this new version of the tests, we define the rules file via the @RulesFile annotation and get our test data from a parameter. Dynamic tests are of course not the only place where ParameterResolver can be used. Other usecases include:

  • Constructors
  • Test Methods
  • BeforeAll
  • BeforeEach
  • AfterEach
  • AfterAll
  • etc.

So, what does an actual ParameterResolver look like?

ParameterResolver classes implement two methods:

  1. boolean supports(...)
    This method will be invoked for all the parameters within your test class. If it returns true the parameter will be resolved using the second method. In this case, we only return true for a Stream<DataSet>, but a single resolver could also handle multiple types of parameters.
  2. Object resolve(...)
    This is the actual resolver for the parameter. It evaluates the @RulesFile annotation of the test method in order to get the name of the file to use. The file is loaded the same way it was in the previous implementation and its contents returned as a Stream<DataSet>.

The Result

When the new tests are executed, the result is the same as earlier:


As you can see, JUnit generated the same tests as before, but this time the input is not loaded with the test. You can check out the example’s code on GitHub. In order to run the tests, you’ll need a current version of IntelliJ, since Eclipse does not support JUnit 5 (yet).

Leave a Comment

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.