0
0
JUnittesting~5 mins

@ParameterizedTest annotation in JUnit

Choose your learning style9 modes available
Introduction

The @ParameterizedTest annotation lets you run the same test many times with different inputs. This helps check if your code works well for many cases without writing many tests.

You want to test a function with many different values quickly.
You want to avoid repeating similar test code for different inputs.
You want to check edge cases and normal cases in one test method.
You want clear test reports showing which input passed or failed.
You want to improve test coverage with less effort.
Syntax
JUnit
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testMethodName(int parameter) {
    // test code using parameter
}

Use @ParameterizedTest above a test method to mark it as parameterized.

Use sources like @ValueSource to provide input values.

Examples
This test runs 3 times, each time with a different fruit name.
JUnit
@ParameterizedTest
@ValueSource(strings = {"apple", "banana", "cherry"})
void testWithStrings(String fruit) {
    assertNotNull(fruit);
}
This test checks that each number is positive.
JUnit
@ParameterizedTest
@ValueSource(ints = {10, 20, 30})
void testWithInts(int number) {
    assertTrue(number > 0);
}
This test uses two parameters per run, checking fruit name length.
JUnit
@ParameterizedTest
@CsvSource({"apple, 5", "banana, 6", "cherry, 6"})
void testWithCsv(String fruit, int length) {
    assertEquals(length, fruit.length());
}
Sample Program

This test runs 3 times, once for each fruit name. It checks that the fruit string is not null.

JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;

public class FruitTest {

    @ParameterizedTest
    @ValueSource(strings = {"apple", "banana", "cherry"})
    void testFruitIsNotNull(String fruit) {
        assertNotNull(fruit);
    }
}
OutputSuccess
Important Notes

Use descriptive test method names to understand what is tested.

Combine @ParameterizedTest with different sources like @ValueSource, @CsvSource, or @MethodSource for flexibility.

Each test run is reported separately, making it easy to see which input failed.

Summary

@ParameterizedTest runs the same test multiple times with different inputs.

It helps test many cases without repeating code.

Use input sources like @ValueSource or @CsvSource to provide test data.