Java

JUnit 5 — Parameterized Tests

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`@ParameterizedTest` runs the same test with multiple inputs. Use `@CsvSource`, `@MethodSource`, or `@EnumSource` for data. Eliminates copy-paste in test classes.
Java
Raw
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.*;
import org.junit.jupiter.params.provider.*;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;

class SlugifyTest {

    // Simple inline values
    @ParameterizedTest
    @ValueSource(strings = {"hello", "world", "java"})
    void notEmpty(String s) { assertFalse(s.isEmpty()); }

    // CSV — input / expected pairs
    @ParameterizedTest(name = "[{index}] slugify({0}) → {1}")
    @CsvSource({
        "Hello World, hello-world",
        "  Trim Me  , trim-me",
        "PHP 8.3,    php-8-3",
        "Café au lait, cafe-au-lait"
    })
    void slugify(String input, String expected) {
        assertEquals(expected, Slug.of(input));
    }

    // Custom argument provider via @MethodSource
    static Stream<Arguments> emails() {
        return Stream.of(
            Arguments.of("alice@example.com", true),
            Arguments.of("plain-text",        false),
            Arguments.of("user@sub.example.com", true)
        );
    }

    @ParameterizedTest
    @MethodSource("emails")
    void validatesEmails(String input, boolean expected) {
        assertEquals(expected, Email.isValid(input));
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.