crmpicco crmpicco - 1 year ago 91
PHP Question

Access class constant dynamically through dataProvider with PHPUnit 5.5.4

I have a bunch of class constants that I would like to check the value of in my PHPUnit test.

When I run this test I get the following error:

1) CRMPiccoBundle\Tests\Services\MailerTest::testConstantValues with
data set "Account Verification" ('ACCOUNT_VERIFICATION',
' Account Verification') Error: Access to undeclared
static property: CRMPiccoBundle\Services\Mailer::$constant

This is my test and its corresponding dataProvider:

* @dataProvider constantValueDataProvider
public function testConstantValues(string $constant, $expectedValue)
$mailer = new Mailer();
$this->assertEquals($expectedValue, $mailer::$constant);

public function constantValueDataProvider()
return [
'Account Verification' => [
' Account Email Verification'

This is how the constant is declared inside

const ACCOUNT_VERIFICATION = ' Account Email Verification';

How can I check the value of this constant?

If I do
inside the test it spits out the expected value, but I would like to do this dynamically with a dataProvider.

Answer Source

ClassName::$property looks up the static property named property on ClassName, rather than the constant with the name stored in $property. PHP does not have a syntax for looking up constants named by string variables; you need to use the class reference in conjunction with the constant() function.

For example:

 * @dataProvider constantValueDataProvider
public function testConstantValues(string $constant, $expectedValue)
    $classWithConstant = sprintf('%s::%s', Mailer::class, $constant);
    $this->assertEquals($expectedValue, constant($classWithConstant));

This is also possible with reflection, but with more code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download