是否可以在每次 PHPUnit 测试失败后运行函数


Is it possible to run a function after every PHPUnit test failure?

我正在使用PHPUnit和Selenium 2在我的Web应用程序上进行一些集成测试。我希望每次测试失败时都保存屏幕截图。这是我到目前为止所拥有的:

<?php
include 'c:/wamp/www/testarea/selenium/phpunit-selenium/vendor/autoload.php';
class WebTest extends PHPUnit_Extensions_Selenium2TestCase
{       
    protected function setUp()
    {
        $this->setBrowser('firefox');
        $this->setBrowserUrl('http://www.google.com/');
    }
    public function testTitle()
    {
        $this->url('http://www.google.com/');
        file_put_contents("c:/wamp/www/testarea/selenium/phpunit-selenium/screenshots/screenshot1.png",$this->currentScreenshot());
        $this->assertEquals('NOT GOOGLE', $this->title());
    }
}

这工作正常,并在测试运行时保存屏幕截图 - 但是,我希望只有在测试失败后才能保存屏幕截图,并且每次测试都应该发生这种情况。有没有办法告诉 PHPUnit 在每次测试失败后自动运行函数?

谢谢

尝试使用方法tearDown()onNotSuccessfulTest()

http://phpunit.de/manual/current/en/fixtures.html

除了Ricardo Simas的答案之外,如果你确实实现了onNotSuccessTest方法,请确保你调用parent,否则默认的错误处理行为将停止发生。

我想知道为什么我的测试在明显存在错误条件(未找到元素)的情况下通过。

例如,我已经把它放在我所有测试用例的祖先类中:

public function onNotSuccessfulTest($e){
    file_put_contents(__DIR__.'/../../out/screenshots/screenshot1.png', $this->currentScreenshot());
    parent::onNotSuccessfulTest($e);
}

要在每次测试失败后运行函数,您可以使用:

onNotSuccessfulTest()    <- Runs after each failed test.
tearDown()               <- Runs after each test.

要在每次成功测试后运行函数,您可以使用:

public function tearDown()
{
    if ($this->getStatus() == 0) {
        // stuff to do on sucsess
    } 
}