Gilbert Pellegrom Gilbert Pellegrom

3rd August 2015

Testing defines in PHPUnit

This one tripped me up recently. Say you are wanting to test a bit of code using PHPunit that relies on a defined constant. You don’t want the define() to affect your other tests, you only want it to apply for this specific test. Something like this:

class MyTest extends PHPUnit\_Framework\_TestCase
{
    public function testExample()
    {
        define( 'EXAMPLEDEFINE', true );
        $result = $this->functionThatReliesOnEXAMPLEDEFINE();
        $this->assertEquals( 'success', $result );
    }
}

At first I figured that @runInSeparateProcess would do the trick. However that didn’t work and after doing some reading I discovered that @preserveGlobalState was also required.

class MyTest extends PHPUnit\_Framework\_TestCase
{
    /\*\*
     \* @preserveGlobalState disabled
     \* @runInSeparateProcess
     \*/
    public function testExample()
    {
        define( 'EXAMPLEDEFINE', true );
        $result = $this->functionThatReliesOnEXAMPLEDEFINE();
        $this->assertEquals( 'success', $result );
    }
}

This worked for me and hopefully will save someone else some time in the future.