2013-02-25 141 views
0

我使用PHPUnit_Selenium延伸和遇到一些不受歡迎的行爲,如果一個元素不存在:PHPUnit_Selenium:如果找不到元素,請不要拋出異常?

Selenium測試案例:

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

測試輸出:

RuntimeException: Invalid response while accessing the Selenium Server at 'http: //localhost:4444/selenium-server/driver/': ERROR: Element id=search not found

所以,我得到一個錯誤,但我想轉換它○失敗代替

我認爲是這樣的:

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
  • Selenium服務器2.30.0

回答

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); 
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擴展以爲其提供自定義異常類。

2

爲什麼不能做這樣的事情:

$元= $這個 - > byId( '搜索');

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

在java中(抱歉,我使用Selenium在Java中),這將引發異常,如果與ID搜索元素沒有找到。我會檢查文檔,看看它是否是在PHP中相同的行爲。否則,你可以嘗試看看如果$元素是有效的,例如:is_null($元素)

+0

您指出我在正確的方向,謝謝! – 2013-03-06 13:37:25

相關問題