使用 PHPUnit 5.5.4 通过 dataProvider 动态访问 class 常量
Access class constant dynamically through dataProvider with PHPUnit 5.5.4
我有一堆 class 常量,我想在我的 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
的静态 属性,而不是名称存储在 $property
中的常量。 PHP 没有查找由字符串变量命名的常量的语法;您需要将 class 引用与 constant()
函数结合使用。
例如:
/**
* @dataProvider constantValueDataProvider
*/
public function testConstantValues(string $constant, $expectedValue)
{
$classWithConstant = sprintf('%s::%s', Mailer::class, $constant);
$this->assertEquals($expectedValue, constant($classWithConstant));
}
这也可以用 reflection,但需要更多代码。
我有一堆 class 常量,我想在我的 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
的静态 属性,而不是名称存储在 $property
中的常量。 PHP 没有查找由字符串变量命名的常量的语法;您需要将 class 引用与 constant()
函数结合使用。
例如:
/**
* @dataProvider constantValueDataProvider
*/
public function testConstantValues(string $constant, $expectedValue)
{
$classWithConstant = sprintf('%s::%s', Mailer::class, $constant);
$this->assertEquals($expectedValue, constant($classWithConstant));
}
这也可以用 reflection,但需要更多代码。