crmpicco crmpicco - 1 year ago 92
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:


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

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


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 Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download