通过Selenium WebDrivervalidation列表元素
WebElement select = myD.findElement(By.xpath("//*[@id='custfoodtable']/tbody/tr[2]/td/div/select")); List 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"); } }
我可以validation列表中的一个元素,但是我需要validation的下拉列表中有20个元素,我不想使用上面的逻辑20次。 有没有更简单的方法呢?
不要使用for-each构造。 它仅在迭代单个Iterable
/数组时有用。 您需要同时迭代List
和数组。
// assert that the number of found
OP之后编辑改变了他的问题:
假设您有一组预期值,您可以这样做:
String[] expected = {"GRAM", "OUNCE", "POUND", "MILLIMETER", "TSP", "TBSP", "FLUID_OUNCE"}; List 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
这段代码基本上是我的第一个代码所做的。 唯一真正的区别在于,现在您手动完成工作并打印出结果。
之前,我使用了JUnit框架的Assert
类中的assertEquals()
静态方法。 此框架是编写Java测试的事实标准, assertEquals()
方法系列是validation程序结果的标准方法。 它们确保传递给方法的参数相等,如果不相等,则抛出AssertionError
。
无论如何,你也可以手动方式,没问题。
你可以这样做:
String[] act = new String[allOptions.length]; int i = 0; for (WebElement option : allOptions) { act[i++] = option.getValue(); } List expected = Arrays.asList(exp); List actual = Arrays.asList(act); Assert.assertNotNull(expected); Assert.assertNotNull(actual); Assert.assertTrue(expected.containsAll(actual)); Assert.assertTrue(expected.size() == actual.size());