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次。有没有更简单的方法呢?
答案 0 :(得分:4)
不要使用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"));
}
假设您有一组预期值,您可以这样做:
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框架的Assert
类中的assertEquals()
静态方法。此框架是编写Java测试的事实标准,assertEquals()
方法系列是验证程序结果的标准方法。他们确保传递给方法的参数是相等的,如果不相等,则抛出AssertionError
。
无论如何,你也可以手动方式,没问题。
答案 1 :(得分:1)
你可以这样做:
String[] act = new String[allOptions.length];
int i = 0;
for (WebElement option : allOptions) {
act[i++] = option.getValue();
}
List<String> expected = Arrays.asList(exp);
List<String> actual = Arrays.asList(act);
Assert.assertNotNull(expected);
Assert.assertNotNull(actual);
Assert.assertTrue(expected.containsAll(actual));
Assert.assertTrue(expected.size() == actual.size());