PHPUnit:如何在特定错误时强制程序退出

PHPUnit: How to force program exit on specific error

如何强制 PHPUnit 完全停止 运行 并在满足特定条件(我自己选择的错误)时退出?实际上,我需要的是类似于下面的内容,除了实际上 PHPUnit 会捕获 exit() 并继续 运行 而不是退出。

// 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.
}

注意:我想继续 运行 正常处理其他错误和失败,因此在我的 XML 文件中设置 stopOnError="true"stopOnFailure="true" 不是我需要的。

我认为您可以通过进行一些覆盖并向基本测试用例添加一些自定义行为来实现此目的 class。

编辑:

正如 OP 在 运行 下面的代码之后发现的那样,调用 exit(1); 而不是 $result->stop() 将导致此时正确终止测试。

尝试以下操作:

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
    }
}

然后在一个测试用例中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
        }
    }
}