How can I write a parameterized test with two arguments in JUnit 5 jupiter? The following does not work (compile error):
@ParameterizedTest @ValueSource(strings = { "a", "b", "foo" }) @ValueSource(ints = { 1, 2, 3 }) public void test(String arg1, int arg2) {...}
Parameterized tests make it possible to run the same test multiple times with different arguments. This way, we can quickly verify various conditions without writing a test for each case. We can write JUnit 5 parameterized tests just like regular JUnit 5 tests but have to use the @ParameterizedTest annotation instead.
JUnit5 Parameterized Test helps to run the same tests multiple times with different arguments/values. They are declared just like the regular @Test method but instead of @Test annotation @ParameterizedTest is used. All supported argument sources are configured using annotations from the org.
JUnit 5, the next generation of JUnit, facilitates writing developer tests with shiny new features. One such feature is parameterized tests. This feature enables us to execute a single test method multiple times with different parameters.
Following are the steps to create parameterized tests in Junit 5. Declare @ParameterizedTest to the test. Declare at least one source (example – @ValueSource ) that will provide the arguments for each invocation of test. Consume the arguments in the test method .
Here are two possibilities to achieve these multi argument test method calls.
The first (testParameters) uses a CsvSource to which you provide a comma separated list (the delimiter is configurable) and the type casting is done automatically to your test method parameters.
The second (testParametersFromMethod) uses a method (provideParameters) to provide the needed data.
@ParameterizedTest @CsvSource({"a,1", "b,2", "foo,3"}) public void testParameters(String name, int value) { System.out.println("csv data " + name + " value " + value); } @ParameterizedTest @MethodSource("provideParameters") public void testParametersFromMethod(String name, int value) { System.out.println("method data " + name + " value " + value); } private static Stream<Arguments> provideParameters() { return Stream.of( Arguments.of("a", 1), Arguments.of("b", 2), Arguments.of("foo", 3) ); }
The output of these test methods are:
Running ParameterTest csv data a value 1 csv data b value 2 csv data foo value 3 method data a value 1 method data b value 2 method data foo value 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With