【问题标题】:Is it possible to run a function after every PHPUnit test failure?每次 PHPUnit 测试失败后是否可以运行一个函数?
【发布时间】:2013-10-10 02:45:56
【问题描述】:

我正在使用 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 在每次测试失败后自动运行一个函数?

谢谢

【问题讨论】:

    标签: php phpunit selenium-webdriver


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      添加到 Ricardo Simas 的回答中,如果您确实实现了 onNotSuccessfulTest 方法,请确保您调用了 parent,否则默认的 error 处理行为将停止发生。

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

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

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

      【讨论】:

      • 在 onNotSuccessfulTest($e) 中截屏之前如何防止浏览器会话关闭?
      • @darkrat 它似乎是自动执行的(可能是由于父调用链在屏幕截图之后?)。你是说它对你来说关闭得太早了,还是你只是想知道?
      • 我发现如果我尝试在 onNotSuccessfulTest($e) 中截屏,浏览器已经关闭并且截屏会引发错误。但是,如果我在 tearDown() 方法中添加以下内容,我可以获得截图if ($this-&gt;hasFailed()) { $file = $this-&gt;screenshot_dir . '/' . get_class($this) . '__' . $this-&gt;getName() . '__' . date('Y-m-d\TH-i-s') . '.png'; file_put_contents($file, $this-&gt;currentScreenshot()); print "Screenshot captured at $file"; }
      • 不知道是不是版本不同?我正在使用 PHPUnit 4.8,但更重要的是这是 Selenium2 和 PHPUnit_Extensions_Selenium2TestCase(因为 Selenium 1 本身会截图)。我正在使用“最后一个”Selenium 2 服务器 2.53.0
      • 另一个想法:是测试失败,还是错误?也许它对错误不起作用。我唯一的 phpunit.xml 配置是 stopOnErrors=true。此项目中的所有其他内容都是默认设置。
      【解决方案3】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-02
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 2011-10-30
        相关资源
        最近更新 更多