问题
I am trying to automate Dual list Box testing. I want to compare the selected values(left side) vs moved values (into right side list). Here is the code.
Select allFromListData = new Select(listData);
// values selection
allFromListData.selectByIndex(0);
allFromListData.selectByVisibleText("Helena");
List<WebElement> selectedList=allFromListData.getAllSelectedOptions();
//clicking on add button
for(int i=0;i<selectedList.size();i++)
System.out.println(selectedList.get(i).getText());
WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
addButton.click();
//Verification of selected content...
WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
Select allToListData = new Select(toListData);
List<WebElement> movedData=allToListData.getOptions();
Question is how to compare the data between List<WebElement> selectedList=allFromListData.getAllSelectedOptions();
and List<WebElement> movedData=allToListData.getOptions();
回答1:
I assume, you want to compare the list of selected items string not the list of web elements as getOptions() method will return list of web elements. Logic is simple, first take the list of values from the list before and after move. Then sort the both of the list of values and compare/assert for equality as given below.
Select allFromListData = new Select(listData);
// values selection
allFromListData.selectByIndex(0);
allFromListData.selectByVisibleText("Helena");
List<WebElement> selectedList=allFromListData.getAllSelectedOptions();
//add selected Items to list
List<String> lstSelectedItem=new ArrayList<String>();
for(int i=0;i<selectedList.size();i++){
System.out.println(selectedList.get(i).getText());
lstSelectedItem.add(selectedList.get(i).getText());
}
//clicking on add button
WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
addButton.click();
//Verification of selected content...
WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
Select allToListData = new Select(toListData);
List<WebElement> movedData=allToListData.getOptions();
//add moved Items to list
List<String> lstMovedItem=new ArrayList<String>();
for(int i=0;i<movedData.size();i++){
System.out.println(movedData.get(i).getText());
lstMovedItem.add(movedData.get(i).getText());
}
//sort the items
Collections.sort(lstSelectedItem);
Collections.sort(lstMovedItem);
//verify the lists are equal
Assert.assertEquals(lstSelectedItem, lstMovedItem);
回答2:
You can try intersection() and subtract() methods from CollectionUtils( java.lang.object).
subtract(Collection a, Collection b)
Returns a new Collection containing a - b.
intersection(Collection a, Collection b)
Returns a Collection containing the intersection of the given Collections.
来源:https://stackoverflow.com/questions/44945522/how-to-compare-to-listwebelement-in-webdriver