我有一堆类常量,我想在我的 PHPUnit 测试中检查它们的值。
当我运行此测试时,出现以下错误:
1) CRMPiccoBundle\Tests\Services\MailerTest::testConstantValues with data set "Account Verification" ('ACCOUNT_VERIFICATION', 'CRMPicco.co.uk Account Verification') Error: Access to undeclared static property: CRMPiccoBundle\Services\Mailer::$constant
这是我的测试及其对应的dataProvider:
/**
* @dataProvider constantValueDataProvider
*/
public function testConstantValues(string $constant, $expectedValue)
{
$mailer = new Mailer();
$this->assertEquals($expectedValue, $mailer::$constant);
}
public function constantValueDataProvider()
{
return [
'Account Verification' => [
'ACCOUNT_VERIFICATION',
'CRMPicco.co.uk Account Email Verification'
]];
}
这是在 Mailer
中声明常量的方式:
const ACCOUNT_VERIFICATION = 'CRMPicco.co.uk Account Email Verification';
如何检查这个常量的值?
如果我在测试中执行 $mailer::ACCOUNT_VERIFICATION
它会吐出预期值,但我想使用 dataProvider 动态执行此操作。
最佳答案
ClassName::$property
在 ClassName
上查找名为 property
的静态属性,而不是名称存储在 中的常量>$属性
。 PHP 没有用于查找由字符串变量命名的常量的语法;您需要将类引用与 constant()
结合使用功能。
例如:
/**
* @dataProvider constantValueDataProvider
*/
public function testConstantValues(string $constant, $expectedValue)
{
$classWithConstant = sprintf('%s::%s', Mailer::class, $constant);
$this->assertEquals($expectedValue, constant($classWithConstant));
}
这也可以用 reflection , 但代码更多。
关于php - 使用 PHPUnit 5.5.4 通过 dataProvider 动态访问类常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39890403/