2015-02-05 50 views
1

在每個測試用例的末尾,我正在通過調用以下代碼來檢查是否存在錯誤。我遇到的問題是,即使不存在錯誤,代碼也會拋出一個NoSuchElementException,並且會導致測試用例失敗。如果出現錯誤,則測試用例會通過。Selenium - NoSuchElementException錯誤檢查

如何修改我的代碼,以便如果不存在錯誤,測試將通過,如果出現錯誤,則測試用例將失敗。

public static void chk_ErrorIsNotEnabled() 
{ 
    try 
    { 
     element = driver.findElement(By.id("ctl00_Content_ulErrorList")); 
     if(element.getText().equals("")) 
     { 
      Log.info("Warning error is not dispayed."); // The test should pass if element is not found 
     } 
     else 
     { 
      Log.error("Warning error is dispayed when it shouldnt be."); 
     } //The test should fail if element is found 
    } 
    catch (NoSuchElementException e){} 
} 

回答

2

的問題是該元素不存在,selenium拋出NoSuchElement異常,最終趕上catch塊,而你的代碼預期元素具有與此ID ctl00_Content_ulErrorList。您不能在不存在的元素上獲取文本。

好的測試將如下所示: 請注意findElements()這裏。它應該找到具有錯誤列表的元素的size。如果是超過0你知道出錯了,並測試將失敗

if(driver.findElements(By.id("ctl00_Content_ulErrorList")).size() > 0){ 
    Log.error("Warning error is dispayed when it shouldnt be."); 
}else{ 
    //pass 
    Log.info("Warning error is not dispayed."); // The test should pass if element is not found 
} 
+1

感謝您的快速回復。奇蹟般有效 – CoffeeTime 2015-02-05 16:14:10

0

您也可以創建由ID爲導航的一種方法,你會重用每次和簡單的斷言應該解決您的問題

private WebElement currentElement;  

public boolean navigateToElementById(String id) { 
    try { 
     currentElement = currentElement.findElement(By.id(id)); 
    } catch (NoSuchElementException nsee) { 
     logger.warn("navigateToElementById : Element not found with id : " 
       + id); 
     return false; 
    } 
    return true; 
}  

然後每次在你測試你可以使用:

assertTrue(navigateToElementById("your id"));