StackPractices
beginner By Mathias Paulenko

Parameterized Test Pattern

How to write parameterized tests to verify the same logic across multiple inputs. Covers pytest parametrize, Jest test.each, JUnit ParameterizedTest, and data providers.

Topics: testing

Overview

Parameterized tests (also called data-driven tests) run the same test logic across a table of input combinations. Instead of writing ten near-identical test functions — one per input — you write the test once and feed it rows of inputs and expected outputs. The framework expands each row into its own reported test case, so test_add[negative_plus_positive] fails on its own line instead of hiding inside a loop’s single pass/fail.

flowchart diagram: Cases[

The payoff is threefold: new cases become one-line additions to the table, the table itself documents the input→behavior contract better than prose ever does, and the framework reports per-case failures so you see the exact input that broke. Every major test framework ships the feature — pytest.mark.parametrize, Jest’s test.each, JUnit 5’s @ParameterizedTest — and the ideas transfer one-to-one between them.

When to Use

  • Testing pure functions with many input-output combinations — validators, parsers, formatters, calculators
  • Edge case testing: null, empty, boundary values, and invalid inputs are exactly the cases developers forget to write a second test for
  • Testing the same behavior across different configurations or environments (the integration-test variant below runs one CRUD suite against several databases)
  • When adding a new test case should be a one-line change — if a colleague can add a case without reading the test body, you’ve got the right shape

When NOT to Use

  • Tests with complex, unique setup per case — when each row needs different mocks or fixtures, the parameter table turns into a config format and separate tests read better
  • Tests that verify interaction (mock calls) rather than output — parameterizing “did X get called” usually obscures which interaction failed
  • When each test case has different assertions — the logic isn’t truly shared, you’re just compressing unrelated tests
  • Tests with side effects that require careful ordering — parameterized cases should be independent; frameworks make no ordering guarantees between them

Solution

pytest parametrize

# Python — pytest.mark.parametrize
import pytest

def add(a, b):
    return a + b

@pytest.mark.parametrize("a, b, expected", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
    (-1, -1, -2),
    (100, 200, 300),
    (0.1, 0.2, 0.3),
])
def test_add(a, b, expected):
    assert add(a, b) == pytest.approx(expected)

pytest parametrize with IDs

# Python — parametrize with test IDs for readable output
@pytest.mark.parametrize("input, expected", [
    ("hello", "HELLO"),
    ("world", "WORLD"),
    ("", ""),
    ("  spaces  ", "  SPACES  "),
    ("CamelCase", "CAMELCASE"),
    ("123abc", "123ABC"),
], ids=[
    "lowercase",
    "word",
    "empty",
    "with_spaces",
    "camelcase",
    "alphanumeric",
])
def test_to_upper(input, expected):
    assert input.upper() == expected

pytest parametrize with multiple parameters

# Python — multiple parameters and edge cases
@pytest.mark.parametrize("email, is_valid", [
    ("alice@example.com", True),
    ("bob@x.com", True),
    ("invalid", False),
    ("@example.com", False),
    ("alice@", False),
    ("alice@.com", False),
    ("", False),
    (None, False),
], ids=[
    "valid_standard",
    "valid_short",
    "no_at_symbol",
    "no_local_part",
    "no_domain",
    "dot_domain",
    "empty_string",
    "none_input",
])
def test_validate_email(email, is_valid):
    assert validate_email(email) == is_valid

Jest test.each (table format)

// JavaScript — Jest test.each with table syntax
describe('add', () => {
  test.each`
    a      | b      | expected
    ${1}   | ${2}   | ${3}
    ${0}   | ${0}   | ${0}
    ${-1}  | ${1}   | ${0}
    ${-1}  | ${-1}  | ${-2}
    ${100} | ${200} | ${300}
  `('returns $expected for $a + $b', ({ a, b, expected }) => {
    expect(add(a, b)).toBe(expected);
  });
});

Jest test.each (array format)

// JavaScript — Jest test.each with array format
describe('validateEmail', () => {
  test.each([
    ['alice@example.com', true],
    ['bob@x.com', true],
    ['invalid', false],
    ['@example.com', false],
    ['alice@', false],
    ['', false],
  ])('validateEmail("%s") returns %s', (email, expected) => {
    expect(validateEmail(email)).toBe(expected);
  });
});

Jest describe.each for grouped tests

// JavaScript — Jest describe.each for grouping
describe.each([
  ['Celsius', 'Fahrenheit', c => c * 9/5 + 32],
  ['Fahrenheit', 'Celsius', f => (f - 32) * 5/9],
])('%s to %s conversion', (from, to, convert) => {
  test.each([
    [0, 32],
    [100, 212],
    [-40, -40],
    [37, 98.6],
  ])('%s° %s = %s° %s', (input, expected) => {
    expect(convert(input)).toBeCloseTo(expected, 1);
  });
});

JUnit 5 ParameterizedTest

// Java — JUnit 5 @ParameterizedTest
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {

    @ParameterizedTest
    @CsvSource({
        "1, 2, 3",
        "0, 0, 0",
        "-1, 1, 0",
        "-1, -1, -2",
        "100, 200, 300",
        "0.1, 0.2, 0.3"
    })
    void testAdd(double a, double b, double expected) {
        assertEquals(expected, calculator.add(a, b), 0.001);
    }

    @ParameterizedTest
    @ValueSource(strings = {"hello", "world", "test", "jest"})
    void testIsNotEmpty(String input) {
        assertFalse(input.isEmpty());
    }

    @ParameterizedTest
    @ValueSource(ints = {1, 2, 3, 5, 8, 13, 21})
    void testIsPositive(int number) {
        assertTrue(number > 0);
    }
}

JUnit 5 with MethodSource

// Java — JUnit 5 @MethodSource for complex 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;

class EmailValidatorTest {

    @ParameterizedTest
    @MethodSource("emailProvider")
    void testValidateEmail(String email, boolean expected) {
        assertEquals(expected, EmailValidator.isValid(email));
    }

    static Stream<Arguments> emailProvider() {
        return Stream.of(
            Arguments.of("alice@example.com", true),
            Arguments.of("bob@x.com", true),
            Arguments.of("invalid", false),
            Arguments.of("@example.com", false),
            Arguments.of("alice@", false),
            Arguments.of("", false),
            Arguments.of(null, false)
        );
    }
}

JUnit 5 with EnumSource

// Java — JUnit 5 @EnumSource for testing all enum values
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;

enum OrderStatus { PENDING, PROCESSING, SHIPPED, DELIVERED, CANCELLED }

class OrderStatusTest {

    @ParameterizedTest
    @EnumSource(OrderStatus.class)
    void testAllStatusesHaveDisplayName(OrderStatus status) {
        assertNotNull(status.getDisplayName());
        assertFalse(status.getDisplayName().isEmpty());
    }

    @ParameterizedTest
    @EnumSource(value = OrderStatus.class, names = {"PENDING", "PROCESSING"})
    void testActiveStatusesCanBeCancelled(OrderStatus status) {
        assertTrue(OrderRules.canCancel(status));
    }

    @ParameterizedTest
    @EnumSource(value = OrderStatus.class, names = {"DELIVERED", "CANCELLED"}, mode = EnumSource.Mode.EXCLUDE)
    void testNonFinalStatusesCanBeModified(OrderStatus status) {
        assertTrue(OrderRules.canModify(status));
    }
}

Python with fixture + parametrize

# Python — combining fixtures with parametrize
@pytest.fixture
def calculator():
    return Calculator()

@pytest.mark.parametrize("expression, expected", [
    ("1 + 2", 3),
    ("10 - 5", 5),
    ("3 * 4", 12),
    ("20 / 4", 5),
    ("2 ** 3", 8),
    ("10 % 3", 1),
])
def test_calculator_operations(calculator, expression, expected):
    assert calculator.evaluate(expression) == expected

@pytest.mark.parametrize("expression", [
    "1 / 0",
    "10 % 0",
    "abc + 1",
    "",
    None,
])
def test_calculator_invalid_input(calculator, expression):
    with pytest.raises((ValueError, TypeError)):
        calculator.evaluate(expression)

Cross-product parametrization

# Python — parametrize multiple dimensions (cross product)
@pytest.mark.parametrize("currency", ["USD", "EUR", "GBP", "JPY"])
@pytest.mark.parametrize("amount", [0, 100, 1000, 10000])
def test_format_currency(amount, currency):
    result = format_currency(amount, currency)
    assert currency in result
    assert str(amount) in result or format(amount, ",") in result

Property-based testing (Hypothesis)

# Python — property-based testing with Hypothesis
from hypothesis import given, strategies as st

@given(st.integers(), st.integers())
def test_add_commutative(a, b):
    assert add(a, b) == add(b, a)

@given(st.integers(), st.integers(), st.integers())
def test_add_associative(a, b, c):
    assert add(add(a, b), c) == add(a, add(b, c))

@given(st.lists(st.integers()))
def test_sum_equals_len_times_mean(numbers):
    if numbers:
        assert sum(numbers) == len(numbers) * (sum(numbers) / len(numbers))

@given(st.text())
def test_upper_lower_roundtrip(s):
    assert s.upper().lower() == s.lower()

Explanation

Under the hood, parameterization is test generation at collection time. When pytest collects test_add, it doesn’t register one test — it registers six, one per row, each with its own name in the report. That’s the whole point versus a for loop inside a test: a loop gives you one pass/fail for the batch and stops at the first failure (or worse, masks it), while generated cases run independently and report individually. Jest’s test.each and JUnit’s @ParameterizedTest do the same thing — expand the template once per row and surface each row as a distinct test node.

Three details matter in practice:

  • Case identity. The framework needs to name each generated test. pytest defaults to test_x[0], test_x[1] — useless when a failure notification lands in Slack at 2 AM. ids (pytest), printf-style templates (Jest), and @DisplayName/source names (JUnit) turn test_add[3] into test_add[negative_plus_negative], which tells you what broke without opening the file.
  • Where the data lives. Inline tables suit small, stable sets. @MethodSource/data providers fit data that needs computing or reusing across tests. External files (CSV, JSON) fit large tables maintained by QA or generated from specs — and they let non-developers contribute cases.
  • Setup scope. Each generated case usually gets fresh fixtures (pytest) or a fresh spec context (JUnit @ParameterizedTest re-runs lifecycle methods per case). That’s the isolation that makes cases order-independent — and the reason shared mutable state between cases is the pattern’s classic footgun.

The natural upgrade path is property-based testing: instead of enumerating cases yourself, you state an invariant (“addition is commutative”) and the framework generates hundreds of inputs, including the edge cases you forgot. Hypothesis and fast-check aren’t replacements for parameterized tests — they’re what you reach for when the input space is too big to enumerate by hand.

Variants

Which variant to pick depends mostly on where the case data lives and how it’s maintained:

  • Inline table (parametrize, test.each, CsvSource) — default choice; data visible next to the test.
  • Method/function source — when cases need computation or reuse across several tests.
  • External file — when the table is large, generated, or maintained by someone who doesn’t touch the test code.
  • Cross-product — stacked decorators covering combinations; powerful but grows quadratically.
  • Property-based — when you’d rather state invariants than enumerate cases.

Data from external file

# Python — load test data from CSV
import csv
import pytest

def load_test_data():
    with open('tests/data/email_cases.csv') as f:
        reader = csv.DictReader(f)
        return [(row['email'], row['expected'] == 'true') for row in reader]

@pytest.mark.parametrize("email, expected", load_test_data())
def test_validate_email_from_csv(email, expected):
    assert validate_email(email) == expected
# tests/data/email_cases.csv
email,expected
alice@example.com,true
bob@x.com,true
invalid,false
@example.com,false

Parameterized with custom names

// JavaScript — Jest with custom test names
describe('fizzbuzz', () => {
  const cases = [
    { input: 1, expected: '1' },
    { input: 3, expected: 'Fizz' },
    { input: 5, expected: 'Buzz' },
    { input: 15, expected: 'FizzBuzz' },
    { input: 30, expected: 'FizzBuzz' },
    { input: 7, expected: '7' },
  ];

  test.each(cases)('fizzbuzz($input) → "$expected"', ({ input, expected }) => {
    expect(fizzbuzz(input)).toBe(expected);
  });
});

Parameterized integration tests

// Java — parameterized integration test with different DB configs
@ParameterizedTest
@MethodSource("databaseConfigs")
void testUserCrudAcrossDatabases(DatabaseConfig config) {
    var repo = new UserRepository(config);
    
    // Create
    User user = repo.save(new User("Alice", "alice@x.com"));
    assertNotNull(user.getId());
    
    // Read
    User found = repo.findById(user.getId());
    assertEquals("Alice", found.getName());
    
    // Update
    found.setName("Alice Smith");
    repo.save(found);
    assertEquals("Alice Smith", repo.findById(user.getId()).getName());
    
    // Delete
    repo.delete(user.getId());
    assertNull(repo.findById(user.getId()));
}

static Stream<DatabaseConfig> databaseConfigs() {
    return Stream.of(
        new DatabaseConfig("h2", "jdbc:h2:mem:test"),
        new DatabaseConfig("sqlite", "jdbc:sqlite::memory:"),
        new DatabaseConfig("postgres", "jdbc:postgresql://localhost/testdb")
    );
}

Best Practices

The pattern’s payoff comes from keeping the table honest: the data should be the only thing that changes between cases. Everything in the test body — setup, invocation, assertion — should apply identically to every row.

  • For a deeper guide, see JUnit 5: Extensions, Parameterized Tests, Dynamic Tests.

  • Use descriptive test IDs — ids in pytest, template strings in Jest, names in JUnit

  • Keep test data readable — align columns, group related cases

  • Test edge cases — null, empty, boundary values, max/min, invalid input

  • Don’t over-parameterize — if each case needs different setup, write separate tests

  • Use pytest.approx for floats — floating point comparisons need tolerance

  • Group by behavior, not by function — test_email_validation not test_validate_email_valid + test_validate_email_invalid

  • Consider property-based testing for mathematical functions — Hypothesis finds edge cases you’d miss

  • Keep parameter lists short — with 8 parameters per row, your function may be too complex

Common Mistakes

  • Too many parameters: 6+ parameters per case makes the table unreadable — nobody can scan a row of nine values and tell which case failed. Extract the inputs into an object or split the test.
  • Testing implementation details: parameterized tests should verify outputs, not which internal calls happened. The moment a case asserts on mock interactions, the table has outgrown the pattern.
  • Missing edge cases: developers fill the table with happy-path rows and forget null, empty, negative, and boundary values — precisely the inputs where bugs live. If every row looks like the previous one, the table is decoration.
  • Not using IDs: test_add[0] tells you nothing when it fails in CI at 2 AM. test_add[zero_plus_zero] tells you exactly which case and why it might matter.
  • Mixing concerns: one parameterized test covering valid and invalid inputs with different assertion logic per row is confusing. Split into test_x_valid and test_x_invalid — two cheap tables beat one clever one.
  • Shared state between cases: a module-level cache or a fixture scoped too broadly lets one generated case pollute the next. Keep fixtures function-scoped and cases independent.

Troubleshooting

  • Case names like test_add[0]/test_add[1] in CI output: you’re on default IDs. Add ids or a name template — debugging a failure should never start with counting rows to find case 7.
  • The suite explodes after stacking decorators: cross-product parametrization multiplies — 4 currencies × 4 amounts × 3 locales is 48 tests from 3 lines. If the suite slows down, keep the cross product for the critical pair and move the rest into separate tables.
  • A case passes alone but fails in the suite: shared mutable state between generated cases (a module-level cache, a fixture with the wrong scope). Make fixtures function-scoped; parameterized cases must not leak into each other.
  • Cases fail on CI but not locally: the data file isn’t on the same path, or floating-point cases lack tolerance. Keep test data under tests/ with a relative path, and compare floats with pytest.approx/equivalents.
  • Adding a case now means editing the test body: the table and the logic have drifted apart — probably assertions that grew per-case branches. Split into two parameterized tests (valid/invalid) rather than if inside the loop body.

See Also

Frequently Asked Questions

What is a parameterized test?

A test that runs the same logic over a table of input-output combinations. Instead of writing 10 test functions, you write 1 and provide a table of 10 cases.

How is this different from a loop inside a test?

A loop inside a test reports one pass/fail for all cases. Parameterized tests report each case separately — you know exactly which input failed.

What is property-based testing?

Instead of providing specific inputs, you define properties (e.g., "addition is commutative") and the framework generates random inputs to verify the property holds. Hypothesis (Python) and fast-check (JavaScript) are popular tools.

Should I use parameterized tests for integration tests?

Yes, when the same workflow applies to different configurations — the example above runs one CRUD suite against three database configs. But avoid it when each configuration needs different setup; that's a sign the tests aren't really the same test.

How many test cases should I have?

Enough to cover all equivalence classes: normal cases, edge cases, boundary values, and error cases. Typically 5-15 cases per parameterized test. Past 50 cases, consider property-based testing.