通过PHPUnit 5.5.4的dataProvider动态访问类常量

3

我有一堆类常量需要在我的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动态地执行此操作。


您能展示一下Mailer类中该常量的声明吗? - BVengerov
1个回答

3

ClassName::$property指的是在ClassName类中查找静态属性property,而不是查找名为$property的常量。PHP没有一种语法可以通过字符串变量查找常量的名称;您需要结合类引用和constant()函数来使用。

例如:

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

使用反射也可以实现这一点,但需要更多的代码。


谢谢,是的,我最初尝试使用“常量”,但这导致了相同的错误(我尝试过使用和不使用“ReflectionClass”)。 - crmpicco
@crmpicco 我更新了我的答案,你需要使用类名进行引用。在你的情况下是否可行? - Matteo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接