When testing class methods, occasionally I need to compare the returned value to some constant defined in some class.
class FooBar
{
const RANDOM = 18;
}
....
// Somewhere in test...
$this->assertEquals(FooBar::RANDOM, $mock->doSomething());
Now as since PHP 7.1 it is possible to define class constants with visibility modifier, this could be changed to:
private const RANDOM = 18;
However, that stops the test from working, as now we are trying to access private constant.
So now we have two options:
- Declare the constant as public.
- Use reflection in test. Meaning the test becomes:
$this->assertEquals(
(new ReflectionClass(FooBar::class))->getConstant('RANDOM'),
$mock->doSomething()
);
The first approach feels very wrong, as we are making constant public only for the sake of test, not because class/hierarchy/business model needs it to be public.
The second one doesn't feel right either, as this use case would not be found by any IDE, so any search/replace/refactor would simply fail here.
So my question(s) is, should the second scenario be used without caring that refactoring will break tests? Or maybe even the use of constants in general should be discouraged in asserts?