Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore exit() and die() with PHPUnit

First of all, the title would suggest this is a duplicate of this or this, but for a couple of reasons, those answers don't work for me, even if my initial problem is the same. I'll explain why.

My problem is this: I have a few occasions in my code where I want to send a header and a body and then terminate processing. Unlike those other questions, I cannot use return or throw an Exception instead (those are obviously different functions designed for different purposes than exit, and this is not an error; it's simply an early runtime termination in some specific cases).

Still, I want to write unit tests that run these methods, make sure that the appropriate headers are set (solution found here), the output body is correct (solved with the $this->expectOutputString()-method in the test case) and then continue testing. In between, the exit will happen.

I've tried the @runInSeparateProcess-annotation in PHPUnit, I've also checked the test_helpers extension, which works, but I don't want to add another extension (be advised that tests will be run in production as well) for one single line of native PHP code that breaks everything. There must be a simpler way without sacrificing best practices.

Does anyone have a good solution to this problem?

like image 930
Helge Talvik Söderström Avatar asked May 28 '14 15:05

Helge Talvik Söderström


1 Answers

I added a variable in the bootstrap that I could reference in the code with an IF in those rare occasions that I need to not exit.

define ('PHPUNIT_RUNNING', 1); 

Normal Program:

if(! @PHPUNIT_RUNNING === 1 )
{
    exit;
}

The PHPUnit is not defined as a rule, so there is a warning generated in PHP execution (which we hide with @. The code will then do what we want when not in test mode. This was added in after the main code was written as we added PHPUnit testing to an existing project, instead of doing TDD.

Please Note:

We do this as sparingly as possible to solve a legacy issue, otherwise we do as others have suggested and throw exceptions or return data to parent functions.

like image 184
Steven Scott Avatar answered Sep 28 '22 06:09

Steven Scott