I have quite a lengthy set up for my test cases, that sits in the @beforeEach
hook.
The issue is that the first method in the @beforeEach
hook, needs to use a different variable, based on what test is running, otherwise I'll have to duplicate the entire test Class to accommodate the variable change, which of of course is not ideal.
My current set up is:
@beforeEach
@afterEach
@Test
@Test
@Test
Essentially, all 3 tests requires a different variable to be injected into the beforeEach hook.
From what I've read, the ParameterResolver
could work, but what I've got seems to throw an exception because I'm using the @Test annotation elsewhere in the class (which I need):
public class ValidListParameterResolver implements ParameterResolver {
private static List<String> LIST_OF_STRINGS_TO_USE = ImmutableList.of("a", "b");
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return true;
}
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return LIST_OF_STRINGS_TO_USE.get(new Random().nextInt(LIST_OF_STRINGS_TO_USE.size()));
}
}
Then in my test Class:
@BeforeEach
@ExtendWith(ValidListParameterResolver.class)
void create(String file) throws IOException {
Type name = method(file);
}
Has anyone achieved this before?
Many thanks for your help.
Here a few tips that may help you get on the right path.
supportsParameter()
should never return true
as a hard-coded value. Rather, a ParameterResolver
must determine whether or not it is supposed to resolve the parameter -- for example, by type or annotation.
Extensions cannot be registered on a @BeforeEach
method (or any other lifecycle method). You will need to register that on the test class with @ExtendWith
.
If you want to know which test method is about to be executed within a @BeforeEach
method, add a TestInfo testInfo
parameter to the @BeforeEach
method's parameter list. You can then access the test Method
in TestInfo
.