禁用错误处理的Phpunit测试非常慢


Phpunit test with disabled error handling is totally slow

我重构了一些代码,并对trigger_error()E_USER_DEPRECATED常量引入了弃用警告。

因此,我需要修改触及该特性的测试

public function testMethod()
{
    $expected = 'value';
    $actual   = $this->subject->callDeprecatedMethod();
    $this->assertEquals($expected, $actual)
}

使方法调用不会引发异常(例如这里或这里列出的):

public function testMethod()
{
    $expected = 'value';
    $save = PHPUnit_Framework_Error_Deprecated::$enabled;
    PHPUnit_Framework_Error_Deprecated::$enabled = false;
    $actual = $this->subject->callDeprecatedMethod();
    PHPUnit_Framework_Error_Deprecated::$enabled = save;
    $this->assertEquals($expected, $actual)
}

这工作得很好,但是我意识到,当运行所有测试时,测试人员在一个点突然花了更长的时间,并通过检查JSON,也在PHPStorm中,这只是改变了testMethod的时间从毫秒上升到0.71秒。

我该如何预防?

我需要我的测试运行得快,快,快:)

看起来在发生错误的情况下,尽管错误异常被禁用,PHPUnit错误处理程序仍然保留一些信息。由于这些回溯可能更大,我假设这是迭代这些并处理数据。

所以我的想法是得到错误处理程序的方程式-由于存储$actual结果变量-并重新启用PHPUnits错误处理程序,然后再次:

public function testMethod()
{
    $expected = 'value';
    $noop = function() {};
    $previous = set_error_handler($noop);
    $actual = $this->subject->callDeprecatedMethod();
    set_error_handler($previous);
    $this->assertEquals($expected, $actual)
}

这将恢复原来的计时。

实际上,类似的效果必须使用错误抑制操作符,正如我后来发现的那样。虽然它没有禁用PHPUnit的处理程序,但快速计时恢复了:

public function testMethod()
{
    $expected = 'value';
    $actual = @$this->subject->callDeprecatedMethod();
    $this->assertEquals($expected, $actual)
}