PHPUnit_Senium:Don';如果找不到元素,是否抛出异常


PHPUnit_Selenium: Don't throw exceptions if element not found?

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

硒测试用例:

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

测试输出:

RuntimeException:访问位于"http://localhost:44444/selenium server/driver/':错误:元素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_Senium 1.2.12
  • Selenium服务器2.30.0

为什么不这样做:

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

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

在java中(对不起,我在java中使用Selenium(,如果找不到id为search的元素,这将引发异常。我会查看文档,看看php中的行为是否相同。否则,您可以尝试查看$元素是否有效,例如:is_null($element(

对于基于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);

好吧,您可以检查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扩展,为其提供一个自定义的异常类。