Under-the-hood functions and methods in PHPUnit
1. Using Data Providers for Elegant Test Cases
I’ll provide a real-life example that already exists in the Laravel framework.
The #[DataProvider] attribute allows the same test logic to run with different inputs, ensuring thorough coverage.
The Test Case: Simplifying with a Data Provider
#[DataProvider('greetingChoiceDataProvider')]
public function testItCanHandleChoiceWithChoiceSeparatorInReplaceString(int $count, string $expected, ?string $locale = null)
{
if (!is_null($locale)) {
$this->app->setLocale($locale);
}
$name = 'Taylor | Laravel';
$this->assertSame(
strtr($expected, [':name' => $name, ':count' => $count]),
$this->app['translator']->choice('tests::app.greeting', $count, ['name' => $name])
);
}
public static function greetingChoiceDataProvider()
{
yield [0, 'Hello :name'];
yield [3, 'Hello :name, you have 3 unread messages'];
yield [0, 'Bonjour :name', 'fr'];
yield [3, 'Bonjour :name, vous avez :count messages non lus', 'fr'];
}
- Each yield defines a test scenario with input values ($count, $expected, and $locale).
- This ensures every edge case is tested without duplicating test logic.