Reputation: 1465
Previously in JUnit4 you could do something like this:
@RunWith(Parameterized.class)
public class MyTest
{
private final int number;
public MyTest(int number) {
this.play = play;
}
@Test
public void testIsEven() {
assertEquals(true, number % 2 == 0);
}
@Test
public void testIsNotOdd() {
assertEquals(false, number % 2 != 0);
}
@Parameterized.Parameters
public static int[] data() {
return new int[] { 2, 4, 6 }
}
}
This would go trough the array, instantiate MyTest
with each of the values and then run all of the tests on each of those instances. See the Parameterized docs for more details.
Now in JUnit5 things have changed, according to the new docs you'd have to write the same tests like this:
public class MyTest {
@ParameterizedTest
@MethodSource("data")
public void testIsEven(int number) {
assertEquals(true, number % 2 == 0);
}
@ParameterizedTest
@MethodSource("data")
public void testIsNotOdd(int number) {
assertEquals(false, number % 2 != 0);
}
public static int[] data() {
return new int[] { 2, 4, 6 }
}
}
You have to repeat the parameter and the data source for each individual test. Is there a way to do something similar as in JUnit4, where the parameterized tests work on instances of the class instantiated with the different parameters?
Upvotes: 6
Views: 5647
Reputation: 10511
(a summary of the comments)
Reusing the same parameters for all/multiple methods in a test class is currently (version 5.3.2 and 5.4.0-M1) not supported. But this is already a request the JUnit team is working on, see
Upvotes: 4
Reputation: 7926
AFAIR junit5 supports meta annotations. You can define a custom annotation and put it on your tests instead:
@MethodSource("data")
@ParameterizedTest
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OldParameterizedTest {
}
public class MyTest {
@OldParameterizedTest
public void testIsEven(int number) {
assertEquals(true, number % 2 == 0);
}
public static int[] data() {
return new int[] { 2, 4, 6 }
}
}
Upvotes: 1
Reputation: 1055
As of today (JUnit 5.3.2 or 5.4.0-M1) it seems not.
I tried to create an Extension
to handle such a case, but test class instantiation happens before TestTemplateInvocationContextProvider
extensions are taken into account.
So it seems not possible to have multiple instantiation contexts for a same test class.
You surely may ask the core team about this by opening an issue on the JUnit5 github repository.
Upvotes: 1