top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Handling Autocomplete and Calendar in Selenium with an overview of different frameworks.

Autocomplete or Auto Suggestion allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values. The auto complete works

with the following input types: text, search, url,email and date pickers.


Let us see how we can handle it. We will be using amazon and google, for example.


Scenario 1: Autocomplete with Amazon

Open the browser

2. Enter the url https://www.amazon.com/

3. Type Samsung in the Search text box


From the drop down let's select samsung tablet with the below snippet

WebDriver driver = new ChromeDriver();

driver.get("http://www.amazon.in"); driver.manage().window().maximize(); driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Samsung"); List<WebElement> searchListAutoComplete = driver .findElements(By.xpath("//*[@id='nav-flyout-searchAjax']/div[1]")); for (WebElement element: searchListAutoComplete) { String searchTexts = element.getText(); System.out.println(searchTexts); if (searchTexts.contains("Samsung Tablet")) { ele.click();

break;


Snippet Explanation :

  • After we send keys to the search bar, we take out the list of elements that are showing below and iterate it using the advanced for a loop.

  • Doing this will yield an element object with which we can get the texts of the suggestions that are coming below.

  • Then using a simple if statement, we can click on the Samsung Tablet using contains method.

Scenario 2 : Autocomplete with Google


Open the browser 2. Enter the url https://www.google.com/ 3. Type Selenium in the Search text box 4. It displays the options for Selenium 5. Select the text ‘Selenium Interview Questions’ from the display options.





driver.get("https://www.google.com/");

driver.findElement(By.id("uh-search-box")).sendKeys("Selenium");

/** Example for Visibility of Elements located by**/

WebDriverWait wait = new WebDriverWait(driver,30);

wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@role='listbox']//li")));

List<WebElement> list = driver.findElements(By.xpath("//ul[@role='listbox']//li"));

System.out.println("Auto Suggest List ::" + list.size());

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

{

System.out.println(list.get(i).getText());

if(list.get(i).getText().equals("selenium interview questions"))

{

list.get(i).click();

break;

}


Conclusion :

These two scenarios provides an overview for handling Autocomplete.Major factor for consideration over here is to predict the exact Xpath of the unordered/ordered list.Once the Xpath is predicted iterating through the list happens using advance for loop


Selenium Frameworks overview :


Data Driven Framework :

Data-driven testing is a test automation technique in which the test data and the test logic are kept separated. The test data drives the testing by getting iteratively loaded to the test script. Hence, instead of having hard-coded input, we have new data each time the script loads the data from the test data source.

Data Driven Testing using @DataProvider:


Data-driven testing can be carried out through TestNG using its @DataProvider annotation. A method with @DataProvider annotation over it returns a 2D array of the object where the rows determine the number of iterations and columns determine the number of input parameters passed to the Test method with each iteration. This annotation takes only the name of the data provider as its parameter which is used to bind the data provider to the Test method. If no name is provided, the method name of the data provider is taken as the data provider’s name.After the creation of data provider method, we can associate a Test method with data provider using ‘dataProvider’ attribute of @Test annotation. For successful binding of data provider with Test method, the number and data type of parameters of the test method must match the ones returned by the data provider method.


Sample code for fetching User registration data from the Excel Sheet(Login Id and Password) using DataProvider method

@DataProvider(name="RegisterData")

public String[][] getdata()throws IOException

{

String path = "/Users/lakshmiparasuraman/eclipse-workspace/ds_AlgoProject/src/test/resources/Testdata/Registerdata.xlsx";

Datafromexcel dataxl = new Datafromexcel(path);

int totalrows = dataxl.getRowCount("Sheet1");

int totalcols = dataxl.getCellCount("Sheet1",1);

String loginData[][]=new String[totalrows][totalcols];

for(int i=1;i<=totalrows;i++)

{

for(int j=0;j<totalcols;j++)

{

loginData[i-1][j]=dataxl.getCellData("Sheet1", i, j);

}

}

return loginData;

}

}


Sample Code for Data Driven Testing in TestNG


@Test(priority=1)

public class SigninTestCase extends Baseclass {


HomePageObject homepage;

GetStartedPageObject getstart;

StackPageObject stack;

ArrayPageObject Array;


public void SignInTest() throws InterruptedException, IOException

{

driver.get(url);

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

logger.info("URl is opened");

GetStartedPageObject getstart = new GetStartedPageObject(driver);

HomePageObject homepage = new HomePageObject(driver);

getstart.getStartedclick();

StackPageObject stack = new StackPageObject(driver);

ArrayPageObject Array = new ArrayPageObject(driver);

SigninPageObject signin = new SigninPageObject(driver);

signin =homepage.clickSignIn();

signin.setUsername(username);

signin.setPassword(password);

homepage = signin.clickSubmit();

Thread.sleep(500);

Assert.assertEquals(homepage.verifyhomepageTitle(), "NumpyNinja","Title not matched");

logger.info("login test passed");

capturescreen(driver,"SignInTest");

System.out.println("End");

}


Framework 2 :PageObject Model


Page Object Model in Selenium

A Page Object Model is a design pattern that can be implemented using Selenium WebDriver. It essentially models the pages/screen of the application as objects called Page Objects. All the functions that can be performed on the specific page are encapsulated in the page object of that screen. In this way any change made in the UI will only affect that screens page object class thus abstracting the changes from the test classes.

Advantages of using the Page Object Model

  • Increases code reusability – Code to work with events of a page is written only once and used in different test cases.

  • Improves code maintainability – Any UI change leads to updating the code in page object classes only leaving the test classes unaffected.

  • Makes code more readable and less brittle

Creating a Page Object Model in Java

Here, we’ll create an automation framework implementing the POM design pattern using Selenium with Java. Suppose we have to test a dummy application with only a login page and a home page. To start with we first need to create page objects for all available pages in our application – LoginPage.java and HomePage.java. Then we will create a test class that will create instances of these page objects and invokes their methods to create tests. Let’s take the scenario of the login page. Here, user enters valid credentials, and on clicking submit button, the user is redirected to the home page.


public class LoginPage { public LoginPage(WebDriver driver) { this.driver = driver; } //Using FindBy for locating elements @FindBy(id = "userName") private WebElement userName; @FindBy(id = "password") private WebElement password; @FindBy(id = "submitButton") private WebElement submit; /*Defining all the user actions that can be performed in the loginPage in the form of methods*/ public void typeUserName(String text) { userName.sendKeys(text); } public void typePassword(String text) { password.sendKeys(text); } /*Take note of return type of this method, clicking submit will navigate user to Home page, so return type of this method is marked as HomePage.*/ public HomePage clickSubmit() { submit.click(); return new HomePage(driver); } public HomePage loginWithValidCredentials(String userName, String pwd) { typeUserName(userName); typePassword(pwd); return clickSubmit(); } }

Framework 3 : Page Factory

PageFactory is class provided by Selenium WebDriver to support the Page Object design pattern. It makes handling “Page Objects” easier and optimized by providing the following-

  1. @FindBy annotation

  2. initElements method

@FindBy

@FindBy annotation is used in PageFactory to locate and declare web elements using different locators. Here, we pass the attribute used for locating the web element along with its value to the @FindBy annotation as parameter and then declare the element. Example-

@FindBy(id="elementId") WebElement element;

In the above example, we have used ‘id’ attribute to locate the web element ‘element’. Similarly, we can use the following locators with @FindBy annotations.

  • className

  • css

  • name

  • xpath

  • tagName

  • linkText

  • partialLinkText

initElements()

The initElements is a static method of PageFactory class which is used in conjunction with @FindBy annotation. Using the initElements method we can initialize all the web elements located by @FindBy annotation. Thus, instantiating the Page classes easily.

initElements(WebDriver driver, java.lang.Class pageObjectClass)

public class HomePageObject {

WebDriver ldriver;

@FindBy(xpath ="//a[text()=' Register ']")

WebElement register;

@FindBy(xpath = "//div[contains(text(),'New Account Created')]")

WebElement NewAccount;

@FindBy(xpath = "//a[contains(text(),'Data Structures')]")

WebElement DataStructuresbtn;

@FindBy(xpath ="//a[text()='Sign out']")

WebElement SignOut;

@FindBy(xpath = "//div[contains(text(),'Logged out')]")

WebElement logoutsuccess;

@FindBy(xpath = "//a[text()='Sign in']")

WebElement signIn;

@FindBy(xpath="//a[@href='stack']")

WebElement stgetstarted;

@FindBy(xpath="//a[@href='array']")

WebElement Argetstarted;

public HomePageObject(WebDriver rdriver)

{

ldriver=rdriver;

PageFactory.initElements(rdriver,this);

}

public String verifyhomepageTitle()

{

return ldriver.getTitle();

}

public String verifyNewAccountCreated()

{

return NewAccount.getText();

}

public RegisterPageObject clickRegister()

{

register.click();

return new RegisterPageObject(ldriver);

}

public void clickDataStructurebutton()

{

DataStructuresbtn.click();

}

public String clickSignOut()

{

SignOut.click();

return logoutsuccess.getText();

}

public SigninPageObject clickSignIn()

{

signIn.click();

return new SigninPageObject(ldriver);

}


public void clickstgetstarted()

{

stgetstarted.click();

}

public void clickArgetstarted()

{

Argetstarted.click();

}

Home Page Test case


public class HomePageTestCase extends Baseclass {

String title;

RegisterPageObject register;

@Test

public void HomepageTest()

{

driver.get(url);

driver.manage().window().maximize();

driver.manage().deleteAllCookies();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));

HomePageObject homepage = new HomePageObject(driver);

GetStartedPageObject getstart = new GetStartedPageObject(driver);

getstart.getStartedclick();

register = homepage.clickRegister();

}

}

Conclusion :

From the above Code Snippets detailed overview of different Selenium frameworks has been descirbed for the homepage and user registration page which happens before Signing into the application.Pros and cons of the different frameworks also defined.




53 views0 comments
bottom of page