crmpicco crmpicco - 2 months ago 9
PHP Question

Correct way to check if a class has a constant defined with PHPUnit

I am trying to find out the best, or correct, way to check if a class has a constant defined with PHPUnit. The PHPUnit docs don't seem to cover this, which makes me wonder if I am doing the correct thing by testing this - however it is an important feature of my class.

I have the following class:

PurchaseManager.php


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


...and part of it's test class has this test:

PurchaseManagerTest.php


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


Is this correct? It passes, but i'm just interested to know if this is accurate and best practice.

I am using PHPUnit 5.0.8.

Answer

I'm using Reflection class for this purpose. It has getConstants method which returns an associative array [<constant_name> => <constant_value>, ...].

Something like:

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