← Back to libraryQuestion 274 of 468
🔬TestNG & JUnitIntermediate

Parameterized Tests in JUnit 5

📌 Definition:

JUnit 5's @ParameterizedTest runs a test once per argument set supplied by a source annotation: @ValueSource, @CsvSource, @CsvFileSource, @MethodSource, or @EnumSource — its data-driven equivalent of TestNG's @DataProvider.

📖 Detailed Explanation:

You annotate the method @ParameterizedTest and add a source: @ValueSource(strings = {"a","b"}) for single values; @CsvSource({"a,1", "b,2"}) for multiple columns; @CsvFileSource for external CSV; @MethodSource("provider") for a method returning a Stream<Arguments> (most flexible, for complex/objects); @EnumSource for enum values. Each invocation reports separately, with a customizable display name. @MethodSource is the closest analog to @DataProvider for rich objects. This makes JUnit 5 fully capable of data-driven testing without TestNG's DataProvider.

🔑 Key Points:
  • @ParameterizedTest + a source annotation runs once per data set
  • @ValueSource/@CsvSource/@CsvFileSource/@EnumSource for simple data
  • @MethodSource(Stream<Arguments>) for complex objects (like @DataProvider)
  • Each invocation reported separately
🌍 Real-World Example:

@ParameterizedTest @CsvSource({"valid,valid,success", "valid,wrong,error"}) void login(String u, String p, String outcome) runs the login test for each row — JUnit 5 data-driven testing in a few lines.

🎯 Scenario-Based Interview Question:

A candidate says 'JUnit can't do data-driven testing like TestNG's DataProvider.' Correct them.