views:

622

answers:

2

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?

+6  A: 

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.

Pascal MARTIN
Yeah, right now I've decided to throw an exception. The problem is my default exception handler is intended to call this function, so I have to create a new exception called killProgramException which my exception handler ignores. Kind of hacky
Zachary Spencer
A: 

I realise you've already accepted an answer for this and it's an old question, but I figure this might be useful for someone, so here goes:

Instead of using die(), you could use throw new RuntimeException() (or an exception class of your own), which will also halt program execution (albeit in a different fashion) and use PHPUnit's setExpectedException() to catch it. If you want your script to die() when that exception is encountered, printing absolutely nothing up at level of the user, take a look at set_exception_handler().

Specifically, I'm thinking of a scenario in which you'd place the set_exception_handler()-call into a bootstrap file that the tests don't use, so the handler won't fire there regardless of scenario, so nothing interferes with PHPUnit's native exception handling.

pinkgothic