CPSAT Mock Exam Questions -Solution 1

Problem from the mock exam:
Here is question 1 from the VAPR182 mock exam
 On, search for the items related to the search keyword. Rearrange the search results in Ascending order of the price.
Test #1: Use keyword “Bedsheets”,
Test #2: Use keyword “Clocks” and
Test #3: Use keyword “Padlocks”.
Save these keywords in an Excel (.xls) file, read the search keywords from this file and then
execute your test.
Write script in TestNG using WebDriver + Google Chrome to test that the results are indeed in Ascending order .
CPSAT believes in practice, and the mock exams are given to prepare you for the exam. If you have not attempted the question on your own, we do recommend that you try to solve the question first before reading any further.
If you run into any issues you can reach out to us via the CPSAT contact us page.
Please note that this is a sample solution for question 1 from the VAPR182 mock exam
* Please note that this may not be the only solution, there could be potentially other ways to solve the problem, specially the way the locators can be handled, data can be handled etc. The intent here is to help you with a sample solution code.
* This is for reference purposes
The question is solved using Java and Maven Project. Here are some details
………………………………………………………………………………………………………………………………………………………..Maven Project Structure is show in image below.

Project has 2 packages, 1 for test scripts (vapr182) and another one for some helping methods (utility) under test.
And, there are 3 folder for the resources that will use in scripts (we will provide the relative path of the resources in the Java code)

  • Data – Excel sheet (we need to read data from .xls or .xlsx files – we will keep the data files here)
  • Drivers – Browser drivers (Drivers to communicate with the browser)
  • Screenshots – If needed during the test scripts

As we know maven is a build tool, if need external librareries in the maven project we define dependency in the pom.xml file and it automatically fetch the libaries from the maven central repository and it keeps in the local repository of the machine.
Here is the URL for the POM.xml file that we have used
Before we start explaining the code and if you want to get access to the data file and the java code, you can download the 3 files we are going to use from the the following URL’s
File 1 – Data File – stored in the src/test/resources/data folder
File 2 – Java Code for the Question 1 – this is in src/test/vapr182 folder (vapr182 is the package name thus)
 File 3 – Java Code for the helper functions used in the above question
Entire Code is explained part by part below
 Part 1 of the code is explained below
We have two member variables, one for WebDriver and another for WebDriverWait class. We will be initializing this in the @Before method and using them in the @Test method
As per the question we are using TestNG framework
[gdlr_code title=”Part1 of code” active=”no”]
* Define member variable for WebDriver and WebDriver Wait
WebDriver driver;
WebDriverWait wait;
public void beforeTest() {
System.out.println(“================Execution Started================”);
System.setProperty(“”, “src\\test\\resources\\drivers\\chromedriver.exe”);
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
wait = new WebDriverWait(driver, 10);
Part 2 of the code is explained below
@DataProvider Annotation is being used to read the excel sheet which has the keywords defined. Please refer the excel sheet URL mentioned above to look at the structure of the file. It has only one column and the keywords for the bedsheet, Clocks and Padlocks are defined in that. We are using a helper function getExcelData which takes the filepath and the sheet name. It returns a 2 dimensional String array which is converted to a 2 dimensional Object Array. TestNG then uses this data provider to call the test as per the number of rows in that. Our excel sheet has three rows and 1 column, so the test will be called three times. The code for the test is in part 3 below.
[gdlr_code title=”Part 2 of the code” active=”no”]
public Object[][] dp() {
String FilePath = “src\\test\\resources\\data\\PepperFry.xls”;
String SheetName = “PepperFry”;
Object [][] excelData = null;
try {
excelData = getExcelData(FilePath, SheetName);
} catch (IOException e) {
return excelData;
 Part 3 of the code is explained below
The 3rd part of the code is the starting of the @Test – and it is using the above DataProvider. As the number of column in the excel sheet is 1, the 2 dimensional array will be of the size 3×1. Hence we need to have only one parameter, which will be populated by the column value from the excel sheet. Hence the below method will be called thrice, once each for “Bedsheet”, “Clocks”, “Padlocks”
The below code begins with opening the website and then clicking on the product search.
It then defines two By objects (locators for SortBy and and lowtohigh elements on the page)
The challenge in the exercise is that there are two popus that come on undefined time and interval and we have no control on knowing how long to wait before the popup comes.
So the code has a while loop and we try more than once (3 times infact) to see if we are able to click on these elements or not in succession.
If we fail, we then assume that the elements are not visible and in that case we have to handle these Popups.
In the while loop, if we are able to click on the two elements, we break from the loop and move to the next part of the code, if not then we try again.
Following are functions defined in the Helper class and in the same class. The code for the same will be explained in sections below.

  1. elementClick(driver, sortBy); (this is a wrapper method, which catches any exception in clicking and returns true or false if the click is successful or not)
  2. handlePopupsException (This method is used to handle the popups on the page)

[gdlr_code title=”Part 3 of the code” active=”no”]
@Test(dataProvider = “dp”)
public void f(String products) {
System.out.println(“Searching for Product = ” + products );
By searchbox =“search”);
WebElement weSearchBox = driver.findElement(searchbox);
By sortBy =“curSortType”);
By lowToHigh = By.xpath(“//*[@id=\”sortBY\”]/li[2]/a”);
int tryCount = 0;
// Following code is done in a while loop till
// the two sortby and  hightolow are clicked
// loop will try three times – in case the clicking does not happen due to some popups
// in that case the test case will fail
while (tryCount <3 ) {
System.out.println(“In the while loop count = ” +  tryCount);
// call the wrapped click function
// This helper function handles visibility and faster page load
// and then returns true or false if click is successful or not
boolean clickedFlag = HelperFunctions.elementClick(driver, sortBy);
// check if the first click is successful
if (clickedFlag) {
// try clicking the lowToHigh
System.out.println(“Clicking on low to high”);
clickedFlag = HelperFunctions.elementClick(driver, lowToHigh);
if (clickedFlag) {
break; // both the elements have been clicked break from while loop
//exception has come and we want to handle the popup
// There are two popups that we might have to handle
// to be on the safer side do a refresh too to get rid of any popups
tryCount++; // increment by 1 so that we can try three times
} // end of while clicking the sort part
Part 4 of the code is explained below
This is the remaining part of the test method.
Once we have clicked on the sortby and lowtohigh we want all the prices to be captured.
Few things we have to take care of

  1. Once the lowtohigh is clicked the page gets refreshed, if we try to get the prices using findElements, these can get stale and when we try to access we may get StaleElementException. Hence we have kept the following in a try catch block, to check the staleness, if not we move ahead.
  2. We then take all the values of the element and using replaceall and parseint get the actual integer price values and store it in an ArrayList of Integer
  3. Later on we use collection.sort on a duplicate list and compare the two verifying that the prices were really sorted or not.

[gdlr_code title=”Part 4 of the code” active=”no”]
// Fetch the prices from the page and add in the list
By proPrice = By.xpath(“//*/span[starts-with(@class,’clip-offr-price’)]”);
WebElement element = driver.findElement(proPrice);
// wait for page to refresh and the webelement to also refresh
try {
catch(Exception e) {
// ignore the exception if the staleness is not found due to refresh
System.out.println(“** Error **” + e.getMessage());
// try to handle popups here too
List <WebElement> actualPrice = driver.findElements(proPrice);
int iSize = actualPrice.size();
System.out.println(“iSize = ” + iSize);
ArrayList<Integer> actualSortedPriceList = new ArrayList<Integer>(iSize);
for(int i=0;i<iSize;i++) {
WebElement wePrice = actualPrice.get(i);
String strPrice = wePrice.getText().replaceAll(“[^0-9]”,””);
int iPrice = Integer.parseInt(strPrice);
//After Sort by ‘Low to High’
System.out.println(“Price list before comparing with the collection sort method”);
for(int obj:actualSortedPriceList)  {
//print a new line
ArrayList<Integer> finalsortedlist = new ArrayList<Integer>(iSize);
finalsortedlist = actualSortedPriceList;
//After Sorting (In Ascending Order)
System.out.println(“Price list After using Colection sort method”);
for(int obj1:finalsortedlist)  {
//print a new line
try {
Assert.assertEquals(actualSortedPriceList, finalsortedlist);
}catch(AssertionError e) {
System.out.println(“Sort By feature ‘Low to High’ is defective”);
Part 5 of the code is explained below
Below method is for handlingPopupsException. There are two popups which may come one occupies the entire page and blocks the execution and other one is in a frame and blocks the sortlowtohigh in the list.
Since the popups may or may not happen, we put a try catch block. This way our test does not stop. If the PopUp comes it will be handled otherwise the code will not block our test.
[gdlr_code title=”Part 5 of the code” active=”no”]
public static void handlePopupsException(WebDriver driver, WebDriverWait wait ) {
try {
// //*[@id=”page”]
By popup1 = By.xpath(“//*[@id=’page’]”);
WebElement wePopup1 = driver.findElement(popup1);;
System.out.println(“##Successfully handled popup1 – method2”);
}catch(Exception e1) {
System.out.println(“##No popup1 displayed ##”);
System.out.println(“Exception ” + e1.getMessage());
System.out.println(“##No popup1 displayed##”);
// //*[@id=”webklipper-publisher-widget-container-notification-close-div“]
try {
// Second popup is in a frame
By frameId =“webklipper-publisher-widget-container-notification-frame”);
WebElement frameElement = driver.findElement(frameId);
By popup2 = By.xpath(“//*[@id=\”webklipper-publisher-widget-container-notification-close-div\”]”);
WebElement wePopup2 = driver.findElement(popup2);
System.out.println(“##Successfully handled popup2”);
}catch(Exception e2) {
System.out.println(“****No popup2 displayed****”);
System.out.println(“Exception ” + e2.getMessage());
System.out.println(“***No popup2 displayed***”);
Part 6 of the code is explained below
Below code is for the Helperfunction for clicking on an element. We have defined a wrapper method which does few smart things

  1. The code waits for the element to be clickable.
  2. As soon as the element is clickable – it stops the page load (by using the following line of code driver.findElement(By.tagName(“body”)).sendKeys(“Keys.ESCAPE”);
  3. And then it clicks on the element

If there is any exception and the element is not clickable, then it returns false otherwise true.
Such wrapper methods are useful as the same code need not be repeated for multiple clicks. This method is used successfully twice when we try to click on the sortyBy and the lowtohigh elements.
[gdlr_code title=”Part 6  of the code” active=”no”]
static int waitTimeinSec = 10;
* Following function is wrapper around for click
* it does two things
* 1. checks if the element is clickable or not
* 2. if it is then tries to stop the page load
* 3. then uses the standard click
* 4. returns true if the click is successful
public static boolean elementClick(WebDriver driver, By byObject) {
// Wait for the element to be clickable
WebDriverWait wait = new WebDriverWait(driver,waitTimeinSec);
try {
// continue even if the page is not loaded
System.out.println(“Clicked on ” + byObject);
return true;
catch (Exception e) {
System.out.println(“Not able to click on ” + byObject);
return false;
} // end of elementClick
 Hope this was helpful.
If you do not understand something or have doubts please get in touch with us using the CPSAT contact page.
In case you have better/elegant solution you can also share with us. We will love to share the same on this page.

Please note that CPSAT is the number 1 certification in Selenium as it is the only globally recognized certificate which assess practical knowledge by posing similar questions.
CPSAT is now the only globally recognized certificate which not only assesses practical knowledge, but the knowledge can  be assessed in three different streams. Java, C# and Python
Happy learning and happy test automation

Leave a Comment