Q:

PHPUnit: How to force program exit on specific error

How can I force PHPUnit to stop running completely and exit when a specific condition (an error of my own choosing) is met?  Effectively, what I need is something like the below, except that in reality PHPUnit traps the exit() and continues running instead of exiting.
// PHPUnit does not alter existing but empty env vars, so test for it.
if (strlen(getenv('APP_HOME')) < 1) {
    $this->fail('APP_HOME set but empty.');
    exit(1);  // <-- Does not work.
}

Note: I want to continue running normally for other errors and failures, hence setting stopOnError="true" or stopOnFailure="true" in my XML file is not what I need.

A:

I think you can achieve this by doing a few overrides and adding some custom behaviour to a base test case class.
EDIT:
As found by the OP after running the below code, calling exit(1); rather than $result->stop() will cause correct termination of the test at that point.
Try the following:
class MyBaseTestCase extends \PHPUnit_Framework_TestCase
{
    // Test this flag at every test run, and stop if this has been set true.
    protected $stopFlag = false;

    // Override parent to gain access to the $result so we can call stop()
    public function run(\PHPUnit_Framework_TestResult $result = null)
    {
        $result = parent::run($result);
        if ($this->stopFlag === true)
        {
            //$result->stop(); // Stop the test for this special case
            exit(1); // UPDATED: This works to terminate the process at this point
        }
        return $result; // return as normal
    }
}

Then in a test case class:
class MyTestCase extends MyBaseTestCase
{
    public function testThisStopsPhpunit()
    {
        if (strlen(getenv('APP_HOME')) < 1) {
            $this->fail('APP_HOME set but empty.');
            $this->stopFlag = true; // Stop further processing if this occurs
        }
    }
}

