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.
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:
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:
So, what does an actual ParameterResolver look like?
thrownewIllegalStateException("Missing @RulesFile annotation on "+executable);
ParameterResolver classes implement two methods:
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.
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>.
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).