只要在应用程序中添加了新案例,我的应用程序就会在表中创建一个新行。该行具有很少的列,列的内容可以与其他列的内容类似。我需要找到行中是否存在“ text ”。以下是我的代码:
@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
答案 0 :(得分: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
}
答案 1 :(得分:0)
您正在从getText()
检索List<WebElement>
- 这就是您收到错误的原因。首先从此列表中获取WemElement
,然后获取其文本:
String caseStatus = null;
if (!newcase.isEmpty())
{
caseStatus = newcase.get(0).getText();
}
...
注意:此代码将从集合中获取第一个元素。您可能需要使用for
循环遍历所有元素:
for (WebElement item : newCase)
{
String text = item.getText();
...
}