Testing / JUnit6 Interview Questions
What are parameterized tests in JUnit 6 and how do you write them?
Parameterized tests run the same test method multiple times with different arguments. In JUnit 6 they are written with @ParameterizedTest and a source annotation that provides the data.
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.*; class ParameterizedDemo { // @ValueSource: simple single-argument tests @ParameterizedTest @ValueSource(ints = {1, 2, 3, 4, 5}) void isPositive(int n) { assertTrue(n > 0); } // @CsvSource: multiple arguments per invocation @ParameterizedTest(name = "{index}: add({0}, {1}) = {2}") @CsvSource({ "1, 2, 3", "10, 20, 30", "-5, 5, 0" }) void additionTest(int a, int b, int expected) { assertEquals(expected, a + b); } // @MethodSource: call a static method returning a Stream @ParameterizedTest @MethodSource("provideStrings") void blankStringsAreRejected(String input) { assertThrows(IllegalArgumentException.class, () -> new Username(input)); } static Stream<String> provideStrings() { return Stream.of("", " ", " ", null); } // @EnumSource: test all or selected enum values @ParameterizedTest @EnumSource(value = Status.class, names = {"PENDING", "PROCESSING"}) void activeStatusesAreNotFinal(Status s) { assertFalse(s.isFinal()); } // @NullSource / @EmptySource / @NullAndEmptySource @ParameterizedTest @NullAndEmptySource void nullAndEmptyAreRejected(String input) { assertThrows(IllegalArgumentException.class, () -> new Username(input)); } }
JUnit 6 display name change: parameterized test names now consistently format arguments as name = value (with spaces around =) instead of JUnit 5's name=value. This affects CI report output and test filtering by name.
More Related questions...