【问题标题】:PHPUnit_Selenium: Don't throw exceptions if element not found?PHPUnit_Selenium:如果找不到元素,不要抛出异常?
【发布时间】:2013-02-10 16:28:17
【问题描述】:

我正在使用PHPUnit_Selenium 扩展,如果元素不存在,我会遇到一些不需要的行为:

硒测试用例:

$this->type('id=search', $searchTerm);

测试输出:

RuntimeException: 在 'http: 访问 Selenium 服务器时响应无效: //localhost:4444/selenium-server/driver/': ERROR: Element id=search not 找到了

所以,我收到一个错误,但我想将其转换为失败

我考虑过这个:

try {
    $this->type('id=search', $searchTerm);
} catch (RuntimeException $e) {
    $this->fail($e->getMessage());
}

但我真的不想将所有运行时异常都转换为失败,也没有找到一种清晰的方法来区分它们。

额外的断言会很棒,但我找不到适合我需要的断言。比如:

$this->assertLocatorExists('id=search'); // ???
$this->type('id=search', $searchTerm);

我错过了什么吗?还是有其他我没有想到的方法?

使用过的版本:

  • PHPUnit 3.7.14
  • PHPUnit_Selenium 1.2.12
  • 硒服务器 2.30.0

【问题讨论】:

    标签: php testing selenium phpunit selenium-webdriver


    【解决方案1】:

    为什么不这样做:

    $element = $this->byId('search');

    //来自https://github.com/sebastianbergmann/phpunit-selenium/blob/master/Tests/Selenium2TestCaseTest.php

    在 java 中(对不起,我在 Java 中使用 Selenium)如果没有找到带有 id 搜索的元素,这将引发异常。我会检查文档以查看它是否与 php.ini 中的行为相同。否则可以尝试查看$element是否有效,例如:is_null($element)

    【讨论】:

      【解决方案2】:

      对于基于SeleniumTestCase的测试用例,我发现以下方法很有用:

      getCssCount($cssSelector)
      getXpathCount($xpath)
      assertCssCount($cssSelector, $expectedCount)
      assertXpathCount($xpath, $expectedCount)
      

      对于基于Selenium2TestCase 的测试用例@Farlan 建议的解决方案应该可以工作,以下方法检索元素并在未找到元素时抛出异常:

      byCssSelector($value)
      byClassName($value)
      byId($value)
      byName($value)
      byXPath($value)
      

      在我的情况下,测试来自SeleniumTestCase,因此问题中示例的解决方案是:

      $this->assertCssCount('#search', 1);
      

      【讨论】:

        【解决方案3】:

        好吧,您可以检查 catch 块中的异常消息文本,如果它不匹配 Element id=search not found(或合适的正则表达式),则重新抛出它。

        try {
            $this->type('id=search', $searchTerm);
        } catch (RuntimeException $e) {
            $msg = $e->getMessage();
            if(!preg_match('/Element id=[-_a-zA-Z0-9]+ not found/',$msg)) {
                throw new RuntimeException($msg);
            }
            $this->fail($msg);
        }
        

        不理想,但可以解决问题。

        我想这说明了为什么应该编写自定义异常类而不是重用标准异常类。

        或者由于它是开源的,当然,您可以随时修改 phpunit Selenium 扩展,为其提供自定义异常类。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-11-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多