Java
@ParameterizedTest
Learn parameterized tests with @ParameterizedTest.
@ParameterizedTest
To run the same test with different inputs, use @ParameterizedTest. With @ValueSource you provide a simple array of values; the test runs once for each value.
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testPositive(int number) {
assertTrue(number > 0);
}
This is cleaner than copying and pasting the same test. Each input is reported as a separate test; if one fails, the others still run. Types like ints, strings, doubles can be used.
Multiple inputs with @CsvSource
When multiple arguments are needed, use @CsvSource. Each row contains comma-separated values; they are passed to the test method as parameters.
@ParameterizedTest
@CsvSource({"2, 3, 5", "4, 4, 8"})
void testAdd(int a, int b, int expected) {
assertEquals(expected, a + b);
}
This provides table-like test data. Each row is a separate scenario and produces its own result. For complex scenarios, @MethodSource with a factory method that returns a Stream can also be used.
Exercise Write a parameterized positive number test
Define a NumberTest class. Write a @ParameterizedTest method testPositive with @ValueSource(ints = {1, 2, 3, 4}); the parameter is int number and the method calls assertTrue(number > 0). Add a main method that loops over 1, 2, 3, checks the same positive condition and prints how many are positive with System.out.println.
Show example solution
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
class NumberTest {
@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 4})
void testPositive(int number) {
assertTrue(number > 0);
}
public static void main(String[] args) {
int count = 0;
for (int n : new int[]{1, 2, 3}) {
if (n > 0) count++;
}
System.out.println(count);
}
}
Test yourself
-
Which annotation is used together with @ParameterizedTest?
- @Test
- @ValueSource
- @BeforeEach
- @DisplayName
Show answer
@ValueSource — @ValueSource provides the input values.
-
Match source annotations
- @ValueSource
- Single-type simple array
- @CsvSource
- Comma-separated rows
- @MethodSource
- Stream factory method
- @EnumSource
- Enum values
-
Complete the ValueSource call
@ParameterizedTest
@____(strings = {"a", "b"})
void testLetter(String s) {
assertNotNull(s);
}
Show answer
@ParameterizedTest
@ValueSource(strings = {"a", "b"})
void testLetter(String s) {
assertNotNull(s);
}
Next lesson: @DisplayName