php - 使用 PHPUnit 5.5.4 通过 dataProvider 动态访问类常量

标签 php unit-testing testing phpunit php-7

我有一堆类常量,我想在我的 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::$propertyClassName 上查找名为 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/

相关文章:

php - 为什么 gettext 将空字符串转换为 .po 标题文本?

php - MySQL 查询 : Getting COUNT of one table where the ID of table 1 has a value of X in a different table

php - PHP中的数组转换

java - 如何测试这条 Camel 路线?依赖注入(inject)和环境变量

testing - 测试场景和测试用例有什么区别?

testing - 使用 Silex 测试框架发送 post 参数

mysql - 使用 PHP 在 MySQL 数据库中插入表情符号 - 智能手机?

c# - FakeItEasy如何设置多个泛型函数的返回值?

c# - 我应该如何断言两个集合的元素相同?

javascript - 你如何定义 npm test 来运行 cucumber 跨平台?