phpphpunit

ArgumentCountError: Too few arguments to function whatever, 0 passed, even with data provider (PHPUnit 12)


I'm trying to use PHPUnit 12 dataProviders to provide data to a function to test but I can't get it working.

Here's my unit test (that lives at tests/TestTest.php):

<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;

final class TestTest extends TestCase
{
    public static function dataProvider(): array
    {
        return [['a'], ['b']];
    }

    #[DataProvider("dataProvider")]
    public function testTest($var): void
    {
        $this->assertTrue(true);
    }
}

When I run ./vendor/bin/phpunit tests I get this:

PHPUnit 12.0.0 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.3.14

E                                                                   1 / 1 (100%)

Time: 00:00.019, Memory: 8.00 MB

There was 1 error:

1) TestTest::testTest
ArgumentCountError: Too few arguments to function TestTest::testTest(), 0 passed in C:\path\to\vendor\phpunit\phpunit\src\Framework\TestCase.php on line 1104 and exactly 1 expected

C:\path\to\tests\TestTest.php:12

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

Any ideas?


Solution

  • Two things good to know:

    1. PhpUnit 10 started to support PHP 8 Attributes. PHPUnit 11 deprecated the older @annotations. PHPUnit 12 removed the @annotations.

    2. PHP Attributes must not be implemented. Then they can't be instantiated. So using a non-existent class-name in an #[ATTRIBUTE-NAME] will simply be unnoticed.

    As you are attributing by DataProvider("dataProvider") to provoke the diagnostics

    1) TestTest::testTest
    ArgumentCountError: Too few arguments to function TestTest::testTest()\
    , 0 passed in C:\path\to\vendor\phpunit\phpunit\src\Framework\TestCase.php on line 1104\
     and exactly 1 expected
    

    it shows that the attribute has no effect. It is a simple typo, the correct classname of the previous @dataProvider annotation is PHPUnit\Framework\Attributes\DataProvider.

    standard class name resolution rules apply, either fully qualify

    #[\PHPUnit\Framework\Attributes\DataProvider(...)])
    public function testMethod(...$arg)
    {
        ...
    }
    

    or alias, in your case

    use PHPUnit\Framework\Attributes\DataProvider;
    

    at the beginning of the (sometimes implicit) namespace segment suffices.