How do you use PHPUnit to test a function if that function is supposed to kill PHP?

It’s obviously an old question but my suggestion would be to move the code that die()‘s into a separate method that you can then mock.

As an example, instead of having this:

class SomeClass
{
    public function do()
    {
        exit(1);
        // or
        die('Message');
    }
}

do this:

class SomeClass
{
    public function do()
    {
        $this->terminate(123);
        // or
        $this->terminate('Message');
    }

    protected function terminate($code = 0)
    {
        exit($code);
    }

    // or 
    protected function terminate($message="")
    {
        die($message);
    }
}

That way you can easily mock the terminate method and you don’t have to worry about the script terminating without you being able to catch it.

Your test would look something like this:

class SomeClassTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @expectedExceptionCode 123
     */
    public function testDoFail()
    {
        $mock = $this->getMock('SomeClass');
        $mock->expects($this->any())
             ->method('terminate')
             ->will($this->returnCallback(function($code) {
                 throw new \Exception($code);
             }));

        // run to fail
        $mock->do();
    }
}

I haven’t tested the code but should be pretty close to a working state.

Leave a Comment