php - 检查类是否具有用 PHPUnit 定义的常量的正确方法

标签 php unit-testing testing phpunit class-constants

我正在尝试找出最佳或正确的方法来检查类是否具有用 PHPUnit 定义的常量。 PHPUnit 文档似乎没有涵盖这一点,这让我想知道我是否通过测试它做了正确的事情 - 然而它是我类(class)的一个重要特征。

我有以下类(class):

PurchaseManager.php

/**
 * Message sent when a course has been purchased
 */
const COURSE_PURCHASED_MESSAGE = 'coursePurchasedMessage';

...它的部分测试类有这个测试:

PurchaseManagerTest.php

public function testCoursePurchasedMessageConstant()
{
    $pm = new PurchaseManager();
    $this->assertTrue(defined(get_class($pm) . '::COURSE_PURCHASED_MESSAGE'));
}

这是正确的吗?它通过了,但我只想知道这是否准确和最佳实践。

我正在使用 PHPUnit 5.0.8。

最佳答案

为此,我正在使用反射类。它有 getConstants返回关联数组的方法 [<constant_name> => <constant_value>, ...] .

类似于:

public function testHasSiteExportedConstant()
{
    $mailer = new \ReflectionClass(SiteExporter::class);
    $this->assertArrayHasKey('SITE_EXPORTED', $mailer->getConstants());
}

关于php - 检查类是否具有用 PHPUnit 定义的常量的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39286371/

相关文章:

php - 我可以将变量传递给函数吗?

php - laravel 用另一个字段更新一个字段

python - 在 unittest 中比较(断言相等)两个包含 numpy 数组的复杂数据结构

ruby-on-rails - cucumber 测试重定向

php - Jquery 或 PHP 根据重复值突出显示表行

c# - 类级别的 TestCategory 而不是测试方法

java - Mockito:如何在不模拟所有参数的情况下轻松 stub 方法

testing - 等待,VBScript

android - Google Play 应用内结算 - 测试 GetPurchases - 静态响应?

php - 无法在 XAMPP 中打开 phpmyadmin