Phpunit 10 has made non-static test providers deprecated. This makes creating test doubles inside the provider problematic, because methods like createMock()
or createStub()
are not static. Here is a fake test demonstrating the issue :
public function provideFake(): array
{
$someDate = $this->createMock(\DateTime::class);
$someOtherDate = $this->createMock(\DateTime::class);
return [
'first test' => [$someDate],
'second test' => [$someOtherDate],
];
}
/**
* @dataProvider provideFake
*/
public function testFake(\DateTime $date): void
{
self::assertTrue(true);
}
Running this test in Phpunit 10 / PHP 8.2 outputs :
There was 1 PHPUnit deprecation : Data Provider method provideFake() is not static
If I change the provider to be static, the result is obviously even worse :
There was 1 PHPUnit error: The data provider specified for testFake is invalid. Using $this when not in object context
I can create the test doubles inside the test itself rather than inside the provider. In this simple example, it doesn't change much because my doubles are just dummies with no set behavior.
But in real life tests, many parameters may be necessary to define this behavior. This means that the provider must output all these parameters instead of just one object, and that the test method must have a very long signature to accept them.
This makes the code much less readable in my opinion.
Is there a way to make a static provider create test doubles ?
callable $setupCallback
and executes it ($foo = $setupCallback($this)
. I don't know if it's a good or bad approach. – Dump