PHPUnit:如何在特定错误上强制程序退出
当满足特定条件(我自己选择的错误)时,如何强制PHPUnit完全停止运行并退出?实际上,我需要的是如下所示的内容,但实际上PHPUnit会捕获PHPUnit:如何在特定错误上强制程序退出,phpunit,Phpunit,当满足特定条件(我自己选择的错误)时,如何强制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()
,并继续运行而不是退出
// 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.
}
//PHPUnit不会更改现有但为空的环境变量,因此请对其进行测试。
if(strlen(getenv('APP_HOME'))<1){
$this->fail('APP_HOME set但为空');
退出(1);//我认为您可以通过执行一些重写并向基本测试用例类添加一些自定义行为来实现这一点
编辑:
正如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 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
}
}
}
MyTestCase类扩展了MyBaseTestCase
{
公共函数测试ThisStopSppunit()
{
if(strlen(getenv('APP_HOME'))<1){
$this->fail('APP_HOME set但为空');
$this->stopfag=true;//如果发生这种情况,请停止进一步处理
}
}
}
这意味着所有测试都将实际启动,但在运行()中停止。
如果$stopfag
为真,是否正确?我有多个文件(类),每个文件(类)都有多个测试用例,所有这些都取决于正确设置的环境变量。我可以使用退出(1)实现我想要的功能
而不是上面的run()
方法中的$result->stop()
行。有趣的是,exit()
在此上下文中正常工作,完全退出phpunit
,而在测试中调用时它是如何不工作的。很高兴您能让它工作。出于兴趣,您调用stop()
得到了什么结果,在第一次失败后它没有终止进一步运行的测试吗?stop()
只停止了当前测试。由于我在多个文件中有一系列测试,其他测试仍会被调用(然后停止)。如果您想编辑答案以包含我们发现的这一点信息,我会将其标记为已接受的答案。