Some applications — especially WordPress — will use PHP constants for configuration that should not be edited directly through the UI.
Normally, a constant cannot be redefined or removed once defined; however, the runkit7 extension exposes functions to modify normally immutable constructs.
Define (or re-define) a constant for the duration of the test.
setConstant(string $key[, mixed $value = null]): self
This is a wrapper around PHP's runkit_constant_redefine()
function.
- $key
- The constant name.
- $value
- The scalar value to set for the constant. Default is
null
This method will return the calling class, enabling multiple methods to be chained.
An AssertWell\PHPUnitGlobalState\Exceptions\RedefineException
will be thrown if the given constant cannot be (re-)defined.
Delete a defined constant for a single test.
deleteConstant(string $key): self
- $key
- The constant name.
This method will return the calling class, enabling multiple methods to be chained.
WordPress enables site owners to enable or disable its debug mode based on a boolean WP_DEBUG
constant. Many plugins may find themselves altering their behavior based on the value of this constant, but this is typically difficult to test.
Imagine we're working on a WordPress plugin that has a debug_comment(string $message)
template function that will print an HTML comment only if WP_DEBUG
is true.
use AssertWell\PHPUnitGlobalState\Constants;
use WP_UnitTestCase;
class MyTestClass extends WP_UnitTestCase
{
use Constants;
/**
* @test
*/
public function a_debug_comment_should_be_shown_if_WP_DEBUG_is_true()
{
$this->setConstant('WP_DEBUG', true);
$this->assertStringContainsString('Test comment', debug_comment('Test comment'));
}
/**
* @test
*/
public function a_debug_comment_should_not_be_shown_if_WP_DEBUG_is_false()
{
$this->setConstant('WP_DEBUG', false);
$this->assertEmpty(debug_comment('Test comment'));
}
}
Regardless of whether or not these tests pass, the WP_DEBUG
constant will be restored to its initial value after each test method completes.