Selenium Web Driver : How to map html elements to Java Object.

3.3k Views Asked by At

As part of Selenium Web-driver learning I came across a scenario. Please let me know the professional approach to proceed.

I am testing a eCommerce application where while I click on Mobile link all mobile phones are getting displayed.I want to check whether they are sorted based on name and price. So basically I need to get Name & price of all elements in the result page.

So My Question is there any way I can map html elements to java value objects ? Any API already available for doing this mapping for me ? Something similar to gson api for converting java objects to their corresponding Json representation ?

Deepu Nair

1

There are 1 best solutions below

2
On BEST ANSWER
//Get all the mobile phones links into a list before sorting

 List<WebElement> mobilelinks=driver.findElements(("locator"));

 Map maps = new LinkedHashMap();//use linked hash map as it preserves the insertion order

 for(int i=0;i<mobilelinks.size();i++){

 //store the name and price as key value pair in map

 maps.put("mobilelinks.get(i).getAttribute('name')","mobilelinks.get(i).getAttribute('price')" );

    }

    /*sort the map based on keys(names) store it in a separate list
      sort the map based on values(prices) store it in a separate list
     */

    /* Using webdriver click the sort by name and compare it with the list which we got after sorting

     and also click sort by prices and compare it with the list*/

To catch an assertion and continue with the test after assertion failures override the Assertion class and create your own CustomAssertion or use SoftAssertions

CustomAssertion.java

public class CustomAssertions extends Assertion {

  private Map<AssertionError, IAssert> m_errors = Maps.newLinkedHashMap();

  @Override
  public void executeAssert(IAssert a) {
    try {
      a.doAssert();
    } catch(AssertionError ex) {
      onAssertFailure(a, ex);
      System.out.println(a.getActual());
      System.out.println(ex.getMessage());
      m_errors.put(ex, a);
    }
  }

  public void assertAll() {
    if (! m_errors.isEmpty()) {
      StringBuilder sb = new StringBuilder("The following asserts failed:\n");
      boolean first = true;
      for (Map.Entry<AssertionError, IAssert> ae : m_errors.entrySet()) {
        if (first) {
          first = false;
        } else {
          sb.append(", ");
        }
        sb.append(ae.getKey().getMessage());
      }
      throw new AssertionError(sb.toString());
    }
  }
}

Instead of using Assertions class to verify the tests use CustomAssertions class

Ex:

//create an object of CustomAssertions class

CustomAssertions custom_assert=new CustomAssertions();

cust_assert.assertTrue(2<1);

cust_assert.assertEquals("test", "testing");

//and finally after finishing the test in aftersuite method call

cust_assert.assertAll();

Hope this helps you if you have any doubts kindly get back...