2013-07-19 108 views
2
验证列表元素
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元。有没有更简单的方法来做到这一点?硒的webdriver

+0

什么是打印效果? –

回答

4

不要使用for-each构造。它仅在迭代单个Iterable /数组时有用。您需要同时迭代List<WebElement>和阵列。 OP的后

// 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测试的事实标准,方法系列是验证程序结果的标准方法。他们确保传递给该方法的参数是相等的,如果不是,他们会抛出一个AssertionError

无论如何,你也可以用手动的方式来做到这一点,没问题。

+0

感谢您的答案家伙..但我dnt知道如果我理解cauz我很新这个。其实我也试过这个 – user2502733

+0

这段代码应该代替你的for-each循环。如果需要,也可以包括您的打印。也就是说,这应该完全按照需要工作,它应该声明你的'元素'值。当你把它粘贴到你的测试中时有什么不对吗?它是否按预期工作?我添加了评论,让您更容易理解代码。 –

+0

嘿,我只是改变我的问题。对于早先的混乱感到抱歉。我只想看看是否有更简单的方法来验证列表中的所有元素。 – user2502733

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());