Reputation: 55
I have added products to my basket and listed their URL in a List and want to verify these products against given String[] of products the items are stored backwards in z String[] so the last item here is the 1st item in the List .. the number of items is 3 and below code works for 2 items and throw invoker exception at the assert method in the third item
public void verifyBag(String[] goods) {
actions.clickOn(By.xpath(bagLocator));
Arrays.sort(goods);
List<WebElement> listItems = actions.driver.findElements(By.xpath(bagItems));
List <String> actualItems = new ArrayList<String>();
for(int i=0;i<listItems.size();i++)
{
actualItems.add(listItems.get(i).getAttribute("href"));
}
int j = goods.length-1;
for(int i=0;i<goods.length;i++)
{
String actualItem = actualItems.get(i);
String product = goods[j];
System.out.println(product);
//assertTrue(actualItems.get(i).contains(goods[j]));
assertTrue(actualItem.equals(product));
j--;
}
assertEquals(listItems.size(), goods.length,"Assert Number of Items in the Bag");
}
Upvotes: 3
Views: 2099
Reputation: 13970
If you don't care about the order, but about the match between provided list of goods
and actualItems
, you can do this:
String[] goods
into some collection, for example List
. Lets call it goodsList
.From goodsList
, remove all items that are also in actualItems
.
goodsList
are
also in actualItems
.actualItems
comparing to goodsList
You can also do the reverse: from actualItems
, remove all items that are also contained in goodsList
. That gives you list of items that were not present in provided list.
Code:
public void verifyBag(String[] goods) {
actions.clickOn(By.xpath(bagLocator));
List<WebElement> listItems = actions.driver.findElements(By.xpath(bagItems));
List <String> actualItems = new ArrayList<String>();
for(int i=0;i<listItems.size();i++)
{
actualItems.add(listItems.get(i).getAttribute("href"));
}
List<String> goodsList = new ArrayList(Arrays.asList(goods));
goodsList.removeAll(actualItems);
if(goodsList.size() == 0) {
// All goods from provided goods list are also in actualItems
}
else {
// Some items didn't match
}
Upvotes: 1
Reputation: 149
You have to check the size of goods
and actualItems
before doing the loop. Make sure that array and list have the same size and both of them is not null or empty.
Function listItems.get(i)
and getAttribute("href")
can return a null value, please check it before add to list.
Upvotes: 0