Skip to main content
Blue Moose logo Blue Moose Field notes
← All articles
code

PHPUnit named datasets with #[DataProvider]

Laptop showing code in an editor

A price parser that reads "1.234" as one euro and change instead of twelve hundred is the classic checkout bug. The usual cause is a parser that was only ever tested with the three inputs its author had in mind, in a loop with a bare assertEquals, so a failure reads "Failed asserting that 123 matches expected 123400" with no hint which input did it. This is the pattern I reach for in that situation: a data provider with named datasets.

The code under test

A small parser that turns messy user-typed prices into integer cents. I never store money as floats, and the parser never returns one.

<?php

declare(strict_types=1);

final class PriceParser
{
    public static function toCents(string $input): int
    {
        $clean = preg_replace('/[^\d,.\-]/', '', $input) ?? '';
        if (!preg_match('/^(-?)([\d.,]*?)(?:[.,](\d{1,2}))?$/', $clean, $m)) {
            throw new \InvalidArgumentException(sprintf('Not a price: "%s"', $input));
        }
        $whole = preg_replace('/\D/', '', $m[2]);
        if ($whole === '' && !isset($m[3])) {
            throw new \InvalidArgumentException(sprintf('Not a price: "%s"', $input));
        }
        $fraction = str_pad($m[3] ?? '', 2, '0');
        $cents = ((int) $whole) * 100 + (int) $fraction;

        return $m[1] === '-' ? -$cents : $cents;
    }
}

Tracing it: the first line strips everything except digits, separators and minus signs. The regex then peels off an optional trailing separator plus one or two digits as the fraction. The lazy *? is what makes "1,234" fall through to "no fraction": the optional group would need to be followed by end-of-string, and ",23" is not. I made the call that three digits after a separator means thousands. That is a business decision, and the tests should say so out loud.

Named datasets with #[DataProvider]

PHPUnit 10 and later reads the attribute #[DataProvider('methodName')], and the provider has to be public static. The old @dataProvider annotation is gone in 12. The detail that matters is the array key. Yield each dataset under a descriptive string and PHPUnit prints it on failure.

<?php

declare(strict_types=1);

use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
use PHPUnit\Framework\TestCase;

final class PriceParserTest extends TestCase
{
    public static function validPrices(): iterable
    {
        yield 'plain integer' => ['12', 1200];
        yield 'dot decimal' => ['12.5', 1250];
        yield 'comma decimal' => ['12,50', 1250];
        yield 'euro, dot thousands' => ['€ 1.234,50', 123450];
        yield 'us style' => ['1,234.50', 123450];
        yield 'thousands, no decimals' => ['1,234', 123400];
        yield 'negative' => ['-3.07', -307];
        yield 'leading zero cents' => ['0.05', 5];
    }

    #[DataProvider('validPrices')]
    public function testParsesValidPrices(string $input, int $expected): void
    {
        $this->assertSame($expected, PriceParser::toCents($input));
    }

    #[TestWith([''], 'empty string')]
    #[TestWith(['abc'], 'no digits')]
    #[TestWith(['1-2'], 'minus in the middle')]
    public function testRejectsGarbage(string $input): void
    {
        $this->expectException(\InvalidArgumentException::class);
        PriceParser::toCents($input);
    }
}

If "thousands, no decimals" breaks, the report reads with data set "thousands, no decimals" instead of with data set #5. That alone repays the extra few characters per line. Using yield instead of returning an array keeps the table readable and lets you generate cases from a loop later. The provider returns iterable, so both work.

#[TestWith] for tiny tables

For the invalid inputs I used #[TestWith]. It is repeatable, takes the dataset as an array and an optional name as the second argument, and keeps the cases right above the method they feed. My rule of thumb: one or two parameters and under about five rows goes inline with #[TestWith]. Anything bigger, or anything several tests share, gets a provider method.

Run it with vendor/bin/phpunit --testdox and every dataset gets its own line in the output. That doubles as a readable spec of the parser's behaviour.

Gotchas

Providers run before the test class is set up, so they cannot touch the container, the database, or anything from setUp(). Keep them to plain values. If you need a service, build it inside the test from the dataset's data. In Drupal, the same holds for kernel and functional tests: yield strings and scalars, resolve entities and services in the test body.

The other trap is false confidence. Named datasets make it easy to pile on rows, and a table of twenty happy-path inputs still tells you nothing about the cases nobody thought of. When a bug report arrives, add the offending input to the table first, watch it fail by name, then fix the parser. The table grows into a record of every mistake the code has made, which is a better use of it than a list of examples I thought up in advance.

BM
Blue Moose
The moose behind Blue Moose. Full-stack PHP developer — Drupal by day, Symfony by night, tests always.