2017-04-07 28 views
-2

我的應用程序中,每當一個新情況是在應用程序中添加的表中創建一個新的行。該行有少量列,列的內容可以與其他列的內容相似。我需要找到,如果「文本」是目前排。以下是我的代碼:如何驗證連續文本的存在。 (斷言VS確認)

@Test (priority = 2) 
public void SaveStatus() 
{ 
    WebElement element = driver.findElement(By.partialLinkText("Case Listing")); //To find 'Case Listing' button on dashboard 
    Actions action = new Actions (driver); 
    action.moveToElement(element); //Move mouse and hover to 'Case Listing' button 
    action.click().build().perform(); //Click on 'Case Listing' button 
    List<WebElement> newcase = driver.findElements(By.xpath("//*[@id='caseList']/tbody/tr[1]"));//find the new case saved in the caselist 
    String CaseStatus = ((WebElement) newcase).getText(); 
    if (CaseStatus.contains("Draft")){ 
    Assert.assertTrue(isTextPresent("Draft")); 
    } 
    System.out.println("Test Case 3 --> Case Status is draft"); 

我需要驗證該行中的「草稿」文本的存在。該文本將始終顯示在4列中。其他行也可以有類似的文字,因此我不想使用getPageSource().contains。這是我得到的錯誤:

java.util.ArrayList cannot be cast to org.openqa.selenium.WebElement

回答

2

問題在以下線存在的,你正在使用的getText()用於webelements。但它只適用於類型webelement。

String CaseStatus = ((WebElement) newcase).getText(); 

您需要使用for循環遍歷列表中的所有webelements並驗證文本。

例子:假設表的ID是caseList

WebElement table_element = driver.findElement(By.id("caseList")); 
    List<WebElement> tr_collection=table_element.findElements(By.xpath("//*[@id='caseList']/tbody/tr")); 

    System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size()); 
    int row_num,col_num; 
    row_num=1; 
    for(WebElement trElement : tr_collection) 
    { 
     List<WebElement> td_collection=trElement.findElements(By.xpath("td")); 
     System.out.println("NUMBER OF COLUMNS="+td_collection.size()); 
     col_num=1; 
     for(WebElement tdElement : td_collection) 
     { 
      System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText()); 
      col_num++; 
     } 
     row_num++; 
    } 

你可以寫你的驗證步驟的上方或下方syso聲明。

System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText()); 

    if (tdElement.getText().contains("Draft")){ 
    // to do something 
    } 
+0

@Sanchit您是否驗證了這一點? – Akarsh

+0

是的。試過這個。現在得到這個錯誤'陳舊元素參考:元素沒有連接到頁面document' – Sanchit

+0

此異常時webelement從DOM破壞會發生。執行調試,在哪一行你得到這個異常。在使用該Web元素之前是否有任何頁面刷新?如果發生,我們需要再次找到元素並對其執行操作。 – Akarsh

0

您是從List<WebElement>檢索getText() - 這就是爲什麼你得到一個錯誤。獲得從這個名單WemElement第一,然後獲取其文本:

String caseStatus = null; 
if (!newcase.isEmpty()) 
{ 
    caseStatus = newcase.get(0).getText(); 
} 
... 

注:此代碼將得到從集合中第一個元素。您可能需要使用通過循環for所有元素進行迭代:

for (WebElement item : newCase) 
{ 
    String text = item.getText(); 
    ... 
} 
+0

瞭解,但我確認文本是否存在? – Sanchit

+0

這仍然不會打印行中存在的全部數據。 – Sanchit

+0

您正在查找'tr'元素。文本可以出現在表單元格中 - 「td」元素。查找並遍歷單元格並獲取文本。以@Akarsh爲例,回答一個示例 –