Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
crmpicco Avatar asked Dec 11 '22 15:12

crmpicco


2 Answers

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());
}
like image 142
BVengerov Avatar answered Jan 25 '23 23:01

BVengerov


I would never test for the existence of a constant, attribute, or method. Unless you are testing a code generator, of course.

like image 24
Sebastian Bergmann Avatar answered Jan 25 '23 23:01

Sebastian Bergmann