Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit return "Data set #0 is invalid." with dataProvider

Tags:

php

phpunit

This simple class return

1) Warning The data provider specified for App\Tests\Twig\GenerateTokenTest::testGenerateToken is invalid. Data set #0 is invalid.

class GenerateTokenTest extends TestCase
{
    /**
     * @dataProvider provideToken
     */
    public function testGenerateToken(int $length): void
    {
        $token = GenerateToken::generate($length);

        $this->assertTrue(true);
    }

    public function provideToken(): iterable
    {
        yield 8;
        yield 16;
        yield 29;
    }
}

Do you know why ?

like image 206
Gaylord.P Avatar asked Jan 29 '19 15:01

Gaylord.P


1 Answers

If you use data providers for PhpUnit, they expect that an array of data is returned on each call. This inner array should match the input variables for your test method. So, if it has that single argument $length, the data provider should return an array containing the test input, like yield [8];

If the test method uses more than a single input variable - you've probably guessed it already: the array should contain more values. As an example, based on your code:

class GenerateTokenTest extends TestCase
{
    /**
     * @dataProvider provideToken
     */
    public function testGenerateToken(int $length, int $size): void
    {
        $token = GenerateToken::generate($length);

        $this->assertTrue(true);
    }

    public function provideToken(): iterable
    {
        yield [8, 9];
        yield [16, 17];
        yield [29, 30];
    }
}
like image 148
Nico Haase Avatar answered Nov 15 '22 05:11

Nico Haase