Search code examples
phpunit-testingphpunit

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


Essentially I have a method of a class called killProgram, which is intended to send a hTTP redirect and then kill PHP.

How am I supposed to test this? When I run phpunit it doesn't return anything for that test, and closes completely.

Right now I'm considering having the killProgram function throw an exception which shouldn't get handled, which would allow me to assert that an exception was thrown.

Is there a better way?


Solution

  • As every tests are run by the same PHPUnit process, if you use exit/die in your PHP code, you will kill everything -- as you noticed ^^

    So, you have to find another solution, yes -- like returning instead of dying ; or throwing an exception (you can test if some tested code has thrown an expected exception).

    Maybe PHPUnit 3.4 and it's --process-isolation switch (see Optionally execute each test using a separate PHP process) might help (by not having everything dying), but you still wouldn't be able to get the result of the test, if PHPUnit doesn't get the control back.

    I've had this problem a couple of times ; solved it by returning instead of dying -- even returning several times, if needed, to go back "high enough" in the call stack ^^
    In the end, I suppose I don't have any "die" anymore in my application... It's probably better, when thinking about MVC, btw.