2

I try to get the kernel root dir in setUp method of unitTest:

private string $databaseDirPath;

protected function setUp(): void
{
    parent::setUp();

    self::bootKernel();
    $container = static::getContainer();
    $this->databaseDirPath = $container->getParameter('kernel.root_dir').'/resources/database/' ;

}
/**
 * @dataProvider provideInexistentFile
 */
public function testConvertReturnNull(string $file):void
{
    if (!file_exists($file) || !is_readable($file)) {
        $response = null;
    }

    $this->assertNull($response);
}

public function provideInexistentFile(): array 
{
    return [
        'inexistent file' => [
            $this->databaseDirPath. 'comdfsasd.csv',
        ],
        'inexistent file' => [
            $this->databaseDirPath. 'gbfdgbzsa.csv',
        ],
    ];
}

and this the error:

$databaseDirPath must not be accessed before initialization

Nicolai Fröhlich
  • 51,330
  • 11
  • 126
  • 130
balda
  • 21
  • 3

2 Answers2

0

Your type-hint for the $databaseDirPath property is incorrect.

The setUp method is not a constructor.

The variable is initialized as null which the type-hint doesn't allow.

Use the following:

private ?string $dateBaseDirPath = null;

Further information can be found in this answer.

Nicolai Fröhlich
  • 51,330
  • 11
  • 126
  • 130
0

Data providers are invoked before any hooks like setUp or beforeClass are executed. So although @Nicolai might be technically correct, with saying your type-hint is incorrect, that's not the root of the issue.

But you could simply add the "data-fetching" to your data provider:

public function provideInexistentFile(): array 
{
    self::bootKernel();
    $container = static::getContainer();
    $databaseDirPath = $container->getParameter('kernel.root_dir') . '/resources/database/';

    return [
        'inexistent file' => [
            $databaseDirPath. 'comdfsasd.csv',
        ],
        'inexistent file' => [
            $databaseDirPath. 'gbfdgbzsa.csv',
        ],
    ];
}
floriankapaun
  • 472
  • 1
  • 4
  • 19