sebastianbergmann / phpunit-documentation-english

English Documentation for PHPUnit
https://docs.phpunit.de/
84 stars 135 forks source link

docs on data providers don't say provided values can't be anonymous functions #361

Open joachim-n opened 2 months ago

joachim-n commented 2 months ago

Trying to use an anonymous function as a value in a data provider crashes phpunit.

The docs should say what the limitations are on possible data provider values.

sebastianbergmann commented 1 month ago

It never occurred to me that one would use anonymous functions as "values" in data providers. That being said, AFAICS it seems to work:

<?php declare(strict_types=1);
namespace PHPUnit\TestFixture;

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

final class DataProviderAnonymousFunctionTest extends TestCase
{
    public static function provider(): array
    {
        return [
            [function () { return true; }],
        ];
    }

    #[DataProvider('provider')]
    public function testOne(callable $a): void
    {
        $this->assertIsCallable($a);
        $this->assertTrue($a());
    }
}
joachim-n commented 1 month ago

I get:

Message: Serialization of 'Closure' is not allowed Location: /var/www/html/vendor/phpunit/phpunit/src/Framework/TestRunner.php:306

But that's on PHPUnit 10.5.20.

Good to know this is supported in 11.

The use case was tests that do nearly everything the same except a few additional steps of setup -- details here https://www.drupal.org/project/drupal/issues/3278083#comment-15666084