Karma Abdelazeez :
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");
}
Kiril S. :
If you don't care about the order, but about the match between provided list of goods
and actualItems
, you can do this:
- Convert input array
String[] goods
into some collection, for exampleList
. Lets call itgoodsList
. From
goodsList
, remove all items that are also inactualItems
.- If resulting set is empty, it means all items from
goodsList
are also inactualItems
. - If resulting set is not empty, it will contain list of items that are missing in
actualItems
comparing togoodsList
- If resulting set is empty, it means all items from
You can also do the reverse: from
actualItems
, remove all items that are also contained ingoodsList
. 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
}