How do I use @EnumSource to test enum values?

@EnumSource is a JUnit 5 parameterized-test source that runs the same test once for each selected enum constant.

Basic usage

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import static org.junit.jupiter.api.Assertions.assertNotNull;

class DirectionTest {

    enum Direction {
        NORTH, SOUTH, EAST, WEST
    }

    @ParameterizedTest
    @EnumSource(Direction.class)
    void shouldTestAllDirections(Direction direction) {
        assertNotNull(direction);
    }
}

This runs the test 4 times: once with NORTH, SOUTH, EAST, and WEST.

Test only specific enum values

Use names to include selected constants:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class DirectionTest {

    enum Direction {
        NORTH, SOUTH, EAST, WEST
    }

    @ParameterizedTest
    @EnumSource(value = Direction.class, names = {"NORTH", "EAST"})
    void shouldTestOnlyNorthAndEast(Direction direction) {
        assertTrue(direction == Direction.NORTH || direction == Direction.EAST);
    }
}

Exclude specific enum values

Use mode = EnumSource.Mode.EXCLUDE:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import static org.junit.jupiter.api.Assertions.assertNotEquals;

class DirectionTest {

    enum Direction {
        NORTH, SOUTH, EAST, WEST
    }

    @ParameterizedTest
    @EnumSource(
        value = Direction.class,
        names = {"WEST"},
        mode = EnumSource.Mode.EXCLUDE
    )
    void shouldTestAllExceptWest(Direction direction) {
        assertNotEquals(Direction.WEST, direction);
    }
}

This runs for NORTH, SOUTH, and EAST.

Match enum names with a regex

Use mode = EnumSource.Mode.MATCH_ANY:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class DirectionTest {

    enum Direction {
        NORTH, SOUTH, EAST, WEST
    }

    @ParameterizedTest
    @EnumSource(
        value = Direction.class,
        names = {"N.*", "E.*"},
        mode = EnumSource.Mode.MATCH_ANY
    )
    void shouldTestNamesStartingWithNOrE(Direction direction) {
        assertTrue(direction.name().startsWith("N") || direction.name().startsWith("E"));
    }
}

This runs for NORTH and EAST.

Common modes

EnumSource.Mode.INCLUDE     // default; include listed names
EnumSource.Mode.EXCLUDE     // exclude listed names
EnumSource.Mode.MATCH_ANY   // include names matching any regex
EnumSource.Mode.MATCH_ALL   // include names matching all regexes

Typical real-world example

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class OrderStatusTest {

    enum OrderStatus {
        NEW, PAID, SHIPPED, CANCELLED
    }

    @ParameterizedTest
    @EnumSource(value = OrderStatus.class, names = {"PAID", "SHIPPED"})
    void completedStatusesShouldBeProcessed(OrderStatus status) {
        assertTrue(status == OrderStatus.PAID || status == OrderStatus.SHIPPED);
    }
}

In short:

@ParameterizedTest
@EnumSource(MyEnum.class)
void test(MyEnum value) {
    // test each enum value
}

How do I use @MethodSource for dynamic test data?

In JUnit 5, @MethodSource lets you supply test arguments from one or more factory methods. It is commonly used with @ParameterizedTest when your test data is too complex for @ValueSource or @CsvSource.

Basic example

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertTrue;

class StringTest {

    @ParameterizedTest
    @MethodSource("blankStrings")
    void shouldDetectBlankStrings(String input) {
        assertTrue(input == null || input.isBlank());
    }

    static Stream<String> blankStrings() {
        return Stream.of(null, "", " ", "\t", "\n");
    }
}

The method referenced by @MethodSource("blankStrings") provides the test data.

Supplying multiple arguments

If your test method has multiple parameters, return Stream<Arguments>.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {

    @ParameterizedTest
    @MethodSource("additionCases")
    void shouldAddNumbers(int a, int b, int expected) {
        assertEquals(expected, a + b);
    }

    static Stream<Arguments> additionCases() {
        return Stream.of(
                Arguments.of(1, 2, 3),
                Arguments.of(5, 7, 12),
                Arguments.of(-1, 1, 0)
        );
    }
}

Using a method source without naming it

If the source method has the same name as the test method, you can omit the method name.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertTrue;

class NumberTest {

    @ParameterizedTest
    @MethodSource
    void isEven(int number) {
        assertTrue(number % 2 == 0);
    }

    static Stream<Integer> isEven() {
        return Stream.of(2, 4, 6, 8);
    }
}

Dynamic test data

You can generate test data dynamically inside the provider method.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.IntStream;

import static org.junit.jupiter.api.Assertions.assertTrue;

class RangeTest {

    @ParameterizedTest
    @MethodSource("numbersFromOneToTen")
    void shouldBePositive(int number) {
        assertTrue(number > 0);
    }

    static IntStream numbersFromOneToTen() {
        return IntStream.rangeClosed(1, 10);
    }
}

Using objects as test data

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertFalse;

class UserValidationTest {

    @ParameterizedTest
    @MethodSource("invalidUsers")
    void shouldRejectInvalidUsers(User user) {
        assertFalse(user.isValid());
    }

    static Stream<Arguments> invalidUsers() {
        return Stream.of(
                Arguments.of(new User("", "[email protected]")),
                Arguments.of(new User("Alice", "")),
                Arguments.of(new User(null, "[email protected]"))
        );
    }

    static class User {
        private final String name;
        private final String email;

        User(String name, String email) {
            this.name = name;
            this.email = email;
        }

        boolean isValid() {
            return name != null && !name.isBlank()
                    && email != null && !email.isBlank();
        }
    }
}

Referencing an external method source

You can also put test data providers in another class.

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

class MathTest {

    @ParameterizedTest
    @MethodSource("com.example.TestData#additionCases")
    void shouldAddNumbers(int a, int b, int expected) {
        assertEquals(expected, a + b);
    }
}
package com.example;

import org.junit.jupiter.params.provider.Arguments;

import java.util.stream.Stream;

public class TestData {

    static Stream<Arguments> additionCases() {
        return Stream.of(
                Arguments.of(1, 2, 3),
                Arguments.of(10, 20, 30)
        );
    }
}

Depending on your setup, make the provider method public static if it is in a different package or class.

Common rules

For standard JUnit 5 usage:

  • The test must use @ParameterizedTest.
  • The provider method usually must be static.
  • The provider method can return:
    • Stream<T>
    • Stream<Arguments>
    • Collection<T>
    • Iterable<T>
    • arrays
    • primitive streams like IntStream, LongStream, or DoubleStream
  • Use Arguments.of(...) when passing multiple values.
  • The number and types of provided arguments must match the test method parameters.

Example with readable test names

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;

class DiscountTest {

    @ParameterizedTest(name = "{index}: price={0}, discount={1}, expected={2}")
    @MethodSource("discountCases")
    void shouldCalculateDiscount(double price, double discount, double expected) {
        assertEquals(expected, price * (1 - discount));
    }

    static Stream<Arguments> discountCases() {
        return Stream.of(
                Arguments.of(100.0, 0.10, 90.0),
                Arguments.of(200.0, 0.25, 150.0),
                Arguments.of(50.0, 0.00, 50.0)
        );
    }
}

In short, use @MethodSource when you want flexible, reusable, or dynamically generated test data for parameterized tests.

How do I use @CsvFileSource to load test data from a file?

Use JUnit 5’s @CsvFileSource with a parameterized test to load rows from a CSV file and pass each row into your test method.

1. Add the CSV file

Place the CSV file under src/test/resources, for example:

src/test/resources/test-data/users.csv

Example CSV:

username,age,active
alice,30,true
bob,25,false
charlie,40,true

2. Use @CsvFileSource

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

class UserCsvTest {

    @ParameterizedTest
    @CsvFileSource(
        resources = "/test-data/users.csv",
        numLinesToSkip = 1
    )
    void loadsUsersFromCsv(String username, int age, boolean active) {
        assertNotNull(username);
        assertTrue(age > 0);

        System.out.println(username + " " + age + " " + active);
    }
}

Key points

  • resources = "/test-data/users.csv" loads the file from the test classpath, usually src/test/resources.
  • The leading / means the path is absolute from the classpath root.
  • numLinesToSkip = 1 skips the header row.
  • Each CSV column maps to a test method parameter.
  • JUnit automatically converts common types like String, int, boolean, double, enums, etc.

CSV with custom delimiter

If your file uses semicolons:

username;age;active
alice;30;true
bob;25;false

Use:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

class UserCsvTest {

    @ParameterizedTest
    @CsvFileSource(
        resources = "/test-data/users.csv",
        numLinesToSkip = 1,
        delimiter = ';'
    )
    void loadsUsersFromCsv(String username, int age, boolean active) {
        // test logic
    }
}

Loading from a filesystem path

If the file is not on the classpath, use files instead of resources:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

class ExternalCsvTest {

    @ParameterizedTest
    @CsvFileSource(
        files = "src/test/resources/test-data/users.csv",
        numLinesToSkip = 1
    )
    void loadsUsersFromFile(String username, int age, boolean active) {
        // test logic
    }
}

Handling empty and null values

Example CSV:

name,email
Alice,[email protected]
Bob,
Charlie,NIL

Example test:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;

import static org.junit.jupiter.api.Assertions.assertNull;

class NullCsvTest {

    @ParameterizedTest
    @CsvFileSource(
        resources = "/test-data/users.csv",
        numLinesToSkip = 1,
        nullValues = "NIL"
    )
    void handlesNullValues(String name, String email) {
        if ("Charlie".equals(name)) {
            assertNull(email);
        }
    }
}

In this example:

  • Empty value after Bob, is treated as an empty string by default in many CSV cases.
  • NIL is explicitly converted to null.

Required dependency

For Maven, make sure you have junit-jupiter-params:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <scope>test</scope>
</dependency>

With Spring Boot tests, this is often already included through spring-boot-starter-test.

How do I use @CsvSource in JUnit parameterized tests?

To use @CsvSource in JUnit 5 parameterized tests, you define multiple sets of comma-separated input values directly inside the annotation. Each CSV row becomes one test invocation.

1. Add the Required Imports

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

@CsvSource is part of JUnit Jupiter Params, so make sure your project includes the parameterized test dependency.

For Maven:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.11.0</version>
    <scope>test</scope>
</dependency>

For Gradle:

testImplementation 'org.junit.jupiter:junit-jupiter-params:5.11.0'

2. Basic @CsvSource Example

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {

    @ParameterizedTest
    @CsvSource({
        "1, 2, 3",
        "5, 7, 12",
        "10, 20, 30"
    })
    void shouldAddTwoNumbers(int a, int b, int expected) {
        int result = a + b;

        assertEquals(expected, result);
    }
}

Each line in @CsvSource maps to the method parameters:

"1, 2, 3"  -> a = 1, b = 2, expected = 3
"5, 7, 12" -> a = 5, b = 7, expected = 12

3. Using Strings with @CsvSource

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import static org.junit.jupiter.api.Assertions.assertEquals;

class StringTest {

    @ParameterizedTest
    @CsvSource({
        "java, JAVA",
        "junit, JUNIT",
        "test, TEST"
    })
    void shouldConvertTextToUppercase(String input, String expected) {
        assertEquals(expected, input.toUpperCase());
    }
}

JUnit automatically converts CSV values to the method parameter types when possible.

4. Handling Commas in Values

If a value contains a comma, wrap it in single quotes:

@ParameterizedTest
@CsvSource({
    "'Smith, John', John",
    "'Doe, Jane', Jane"
})
void shouldExtractFirstName(String fullName, String firstName) {
    String result = fullName.substring(fullName.indexOf(",") + 2);

    assertEquals(firstName, result);
}

Here, 'Smith, John' is treated as one argument instead of two.

5. Using Custom Delimiters

By default, @CsvSource uses a comma. You can change the delimiter:

@ParameterizedTest
@CsvSource(
    value = {
        "1|2|3",
        "4|5|9",
        "10|20|30"
    },
    delimiter = '|'
)
void shouldAddNumbersWithCustomDelimiter(int a, int b, int expected) {
    assertEquals(expected, a + b);
}

6. Null and Empty Values

JUnit treats an unquoted empty value as null:

@ParameterizedTest
@CsvSource({
    "apple, APPLE",
    ", UNKNOWN"
})
void shouldHandleNullValues(String input, String expected) {
    String result = input == null ? "UNKNOWN" : input.toUpperCase();

    assertEquals(expected, result);
}

You can use an empty string by quoting it:

@ParameterizedTest
@CsvSource({
    "'', empty"
})
void shouldHandleEmptyString(String input, String expected) {
    String result = input.isEmpty() ? "empty" : input;

    assertEquals(expected, result);
}

7. Adding Display Names

You can make test output easier to read using the name attribute:

@ParameterizedTest(name = "{index} => input={0}, expected={1}")
@CsvSource({
    "java, JAVA",
    "junit, JUNIT"
})
void shouldConvertToUppercase(String input, String expected) {
    assertEquals(expected, input.toUpperCase());
}

Example display names:

1 => input=java, expected=JAVA
2 => input=junit, expected=JUNIT

Key Points

  • Use @ParameterizedTest, not @Test.
  • Use @CsvSource to provide multiple comma-separated argument sets.
  • Each CSV row must match the number of method parameters.
  • JUnit automatically converts values to types like int, double, boolean, String, and enums.
  • Use single quotes for values containing commas.
  • Use quoted empty strings for ""; unquoted empty values are treated as null.
  • Use delimiter if comma-separated data is hard to read.

How do I use @ValueSource in JUnit parameterized tests?

In JUnit 5, @ValueSource is used with @ParameterizedTest to run the same test multiple times with different simple literal values.

Basic example

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class StringTest {

    @ParameterizedTest
    @ValueSource(strings = {"racecar", "radar", "level"})
    void palindromeWordsHaveLengthGreaterThanZero(String word) {
        assertTrue(word.length() > 0);
    }
}

This test runs 3 times, once for each value:

racecar
radar
level

Supported @ValueSource types

@ValueSource supports arrays of simple values such as:

@ValueSource(strings = {"apple", "banana"})
@ValueSource(ints = {1, 2, 3})
@ValueSource(longs = {10L, 20L})
@ValueSource(doubles = {1.5, 2.5})
@ValueSource(booleans = {true, false})
@ValueSource(chars = {'a', 'b'})
@ValueSource(classes = {String.class, Integer.class})

Example with integers:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class NumberTest {

    @ParameterizedTest
    @ValueSource(ints = {2, 4, 6, 8})
    void numbersAreEven(int number) {
        assertTrue(number % 2 == 0);
    }
}

Important limitation

@ValueSource can provide only one argument per test invocation.

So this works:

@ParameterizedTest
@ValueSource(strings = {"hello", "world"})
void testSingleArgument(String value) {
    // test logic
}

But this does not work with @ValueSource:

@ParameterizedTest
@ValueSource(strings = {"hello", "world"})
void testMultipleArguments(String input, int expectedLength) {
    // invalid for @ValueSource
}

For multiple arguments, use @CsvSource, @MethodSource, or @ArgumentsSource.

Example with empty and blank strings

@ValueSource can be combined with other parameter sources:

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EmptySource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertTrue;

class BlankStringTest {

    @ParameterizedTest
    @NullSource
    @EmptySource
    @ValueSource(strings = {" ", "   ", "\t", "\n"})
    void stringIsBlank(String value) {
        assertTrue(value == null || value.isBlank());
    }
}

This runs with:

null
""
" "
"   "
"\t"
"\n"

Maven dependency

Make sure you have JUnit Jupiter Params on the test classpath:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <scope>test</scope>
</dependency>

If you use Spring Boot, this is usually included through:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Summary

Use @ValueSource when your parameterized test needs one simple value per run:

@ParameterizedTest
@ValueSource(strings = {"a", "b", "c"})
void test(String value) {
    // runs once for each value
}