通过Selenium WebDriver验证列表元素

WebElement select = myD.findElement(By.xpath("//*[@id='custfoodtable']/tbody/tr[2]/td/div/select"));

List<WebElement> allOptions = select.findElements(By.tagName("option"));

for (WebElement option : allOptions) {

System.out.println(String.format("Value is: %s", option.getAttribute("value")));

option.click();

Object vaLue = "Gram";

if (option.getAttribute("value").equals(vaLue)) {

System.out.println("Pass");

} else {

System.out.println("fail");

}

}

我可以验证列表中的一个元素,但是下拉菜单中有20个元素需要验证,我不想使用上述逻辑20次。有没有更简单的方法可以做到?

回答:

不要使用for-each构造。仅在对单个Iterable/数组进行迭代时有用。您需要同时遍历List<WebElement>和数组。

// assert that the number of found <option> elements matches the expectations

assertEquals(exp.length, allOptions.size());

// assert that the value of every <option> element equals the expected value

for (int i = 0; i < exp.length; i++) {

assertEquals(exp[i], allOptions.get(i).getAttribute("value"));

}


OP稍微改变了他的问题后进行编辑:

假设您有一组期望值,则可以执行以下操作:

String[] expected = {"GRAM", "OUNCE", "POUND", "MILLIMETER", "TSP", "TBSP", "FLUID_OUNCE"};

List<WebElement> allOptions = select.findElements(By.tagName("option"));

// make sure you found the right number of elements

if (expected.length != allOptions.size()) {

System.out.println("fail, wrong number of elements found");

}

// make sure that the value of every <option> element equals the expected value

for (int i = 0; i < expected.length; i++) {

String optionValue = allOptions.get(i).getAttribute("value");

if (optionValue.equals(expected[i])) {

System.out.println("passed on: " + optionValue);

} else {

System.out.println("failed on: " + optionValue);

}

}

这段代码实质上完成了我的第一个代码。唯一的区别是,现在您手动进行工作并打印结果。

以前,我使用了JUnit框架类中的assertEquals()静态方法Assert。该框架是编写Java测试的实际标准,assertEquals()方法家族是验证程序结果的标准方法。它们确保传递给方法的参数相等,如果不相等,则抛出AssertionError

无论如何,您也可以手动进行操作,也没有问题。

以上是 通过Selenium WebDriver验证列表元素 的全部内容, 来源链接: utcz.com/qa/402671.html

回到顶部