I know I can use dataProvider like so:
use PHPUnit\Framework\TestCase;
class DataProviderSetupTest extends TestCase {
/**
* @dataProvider basicDataProvider
*/
public function testDataProvider(string $expected): void
{
$actualResult = 'I am the value!'; // generated by some service under test
$this->assertSame($expected, $actualResult);
}
public function basicDataProvider(): \Generator
{
yield 'no state, all fine' => ['I am the value!'];
}
}
This test will run fine.
Yet if I have a property on the test class which is initialzied via setUp, it is null when the dataProvider is executed:
use PHPUnit\Framework\TestCase;
class DataProviderSetupTest extends TestCase
{
protected string $state;
protected function setUp(): void
{
$this->state = 'Thank you for the fish!';
}
/**
* @dataProvider statefulDataProvider
*/
public function testDataProviderWithStateDependency(string $expected): void
{
$actualResult = 'Thank you for the fish!'; // generated by some service under test
$this->assertSame($expected, $actualResult);
}
public function statefulDataProvider(): \Generator
{
yield 'member not initialized' => [$this->state];
}
}
This test will fail:
The data provider specified for DataProviderSetupTest::testDataProviderWithStateDependency is invalid.
Error: Typed property DataProviderSetupTest::$state must not be accessed before initialization
How to initialize test classes members so that I can use them within data providers?
I also tried setUpBeforeClass yet since that one is static, I cannot set member variables.
My phpunit version is 9.6.11.