Selenium Interview Questions

Just spend just 10 minutes every day to master the top Selenium interview questions. This ultimate list of Selenium interview questions and answers will help you to answer on the topics like different Locators supported in Selenium, ways to upload a file using AutoIt tool, the difference between driver.findElement() and driver.findElements() commands, Selenese and different types of Selenese, Page Object Model in Selenium, etc. Start preparing these Selenium technical interview questions and answers, which are for freshers as well as for experienced, and this will land you a good job as a Quality Assurance Engineer or Senior Quality Analyst.

  • 4.7 Rating
  • 50 Question(s)
  • 30 Mins of Read
  • 7651 Reader(s)

Beginner

Selenium can only be used to test/automate web-based applications. It cannot be used to automate desktop applications.

Selenium WebDriver doesn’t have an inbuilt data-driven testing mechanism. This means the user needs to manually connect automated tests to external data sources.

Selenium doesn't support testing on images. It needs to be integrated with Sikuli for image-based testing

There is no native reporting capability. This can be resolved by integrating it with frameworks like TestNG /JUnit

A Windows-based popup cannot be tested using Selenium alone. AutoIT needs to be used to handle the windows based popups.

Selenium is an open source so there is no dedicated support available for it.

Selenium doesn’t have built-in object repository.

Selenium web driver uses below 8 locators to find the elements on the web page:

  • id – used to select the element with a specified @id attribute.
  • name – used to Select the first element with the specified @name attribute.
  • linkText - used to select link /anchor tag element which contains the matching text
  • PartialLinkText – used to select link (anchor tag) element which contains text matching the specified partial link text.
  • tagName – used to locate the element using its HTML Tag
  • className – used to locate the Element using a class Name
  • cssSelector - used to locate the element using CSS selectors
  • xpath – used to locate the element using an XPath expression.

WebDriver is an Interface. We need to create an Object of the required driver class such as FirefoxDriver, ChromeDriver, InternetExplorerDriver etc.

Syntax to launch Firefox Driver: 

WebDriver driver = 
new FirefoxDriver();
Also to use geckodriver with Selenium, upgrade to Selenium 3.x or higher version  and set the property as follows:
System.setProperty("webdriver.gecko.driver", 
"D:\\Selenium Environment\\Drivers\\geckodriver.exe");

Syntax to launch Chrome Driver: 

WebDriver driver = new 
ChromeDriver();

Syntax to launch Internet Explorer Driver: 

WebDriver driver = new 
InternetExplorerDriver();

Syntax to launch Safari Driver: 

WebDriver driver = new 
SafariDriver();

driver.navigate().forward(); – used to navigate to the next web page with reference to the browser’s history

driver.navigate().back(); – used to take back to the previous web page with reference to the browser’s history

driver.navigate().refresh(); – used to to refresh the current web page i.e. reloading all the web elements

driver.navigate().to(“url”); – used to launch a new web browser window and navigate to the specified URL .

Intermediate

driver.get("URL") and driver.navigate().to("URL")  both these commands are used to navigate to a URL passed as parameter.

There is a very little difference between the two commands-

driver.navigate() command maintains browser history or cookies to navigate back and forward and allows you moving back and forward in browser history using driver.navigate().forward() and driver.navigate().back() commands. driver.navigate() command used to navigate to the particular URL and it does not wait to page load.

In the case of a single page application, where the URL is appended by '#' to navigate to a different section of the page, driver.navigate().to() navigates to a particular page by changing the URL without refreshing the page whereas the driver.get() refreshes the page also and waits for the page to load. This refreshing of the page is also the primary reason because of which history is not maintained in the case of the driver.get() command.

Some of the commonly used expected conditions of an element that can be used with explicit waits are-

  • elementToBeClickable(WebElement element or By locator) - An expectation for checking an element is visible or not and enabled so that you can click on it.
  • stalenessOf(WebElement element) - will Wait until an element is no longer attached to the DOM or timeout expires.
  • visibilityOf(WebElement element) - visibilityOf(WebElement element) is used for checking that an element is present on the DOM of a page and visible.
  • visibilityOfElementLocated(By locator) - Used to check if the element is present on the DOM of a page and it is visible.
  • invisibilityOfElementLocated(By locator) - invisibilityOfElementLocated(By locator) used for checking an element is invisible or not present in the DOM.
  • attributeContains(WebElement element, String attribute, String value)  - Waits for a certain text fragment to appear in the attribute.
  • alertIsPresent() - alertIsPresent(), accepts any present alert. and returns true if there is an alert to click
  • titleContains(String title) -  titleContains(String title) used for checking that the title of a page contains a case-sensitive substring.
  • titleIs(String title) - wait till the title of the page is the same as mentioned in the attribute. 
  • textToBePresentInElementLocated(By, String) - wait till expected text appears on targeted element.

Some of the commonly seen exceptions in selenium are-

  1. NoSuchElementException -  You get this exception when the locator mentioned in the Selenium Program code is unable to find the web element on the web page.
  2. ElementNotVisibleException - You get this exception when a WebDriver is able to locate web elements on the current webpage but it is not visible on the screen.
  3. NoAlertPresentException - You get this exception when we try to switch to an alert but the targeted alert is not present.
  4. InvalidElementStateException - You get this exception when the state of an element is not appropriate for the desired action.
  5. NoSuchAttributeException - You get this exception when you are trying to fetch an attribute's value but the attribute is not correct.
  6. WebDriverException - You get this exception when there is an issue with driver instance preventing it from getting launched.
  7. NoSuchFrameException - You get this exception when you try to switch to a frame but the targeted frame is not present.
  8. NoSuchWindowException - You get this exception when you try to switch to a window but the targeted window is not present.
  9. UnexpectedAlertPresentException - You get this exception when an unexpected alert blocks the normal interaction of the driver.
  10. TimeoutException - You get this exception when a command execution gets a timeout.

POM that is Page Object Model is a design pattern popular in selenium to create object repository for web UI elements. It is a widely used design pattern for enhancing test maintenance and to avoid code duplication. It can be used in a type of framework such as modular, data-driven, keyword-driven, etc. POM is an object-oriented class works as an interface to the page for application under test. Under the page object model, for each web page in the application, there must be a corresponding page class. Web element of that web page will be identified by page class and this page class also contains Page methods which perform operations on those WebElements. As per the task performed by these methods, the name of these methods is given.

POM allows Operations. POM concept makes the test scripts cleaner and easy to understand. With the help of POM, the object repository is created independent of test cases, so you can use the same object repository for a different purpose with different tools. We can integrate POM with TestNG/JUnit for functional testing and as well as with JBehave/Cucumber for acceptance testing.

Using POM an Object Repository can be created and can be maintained in the separate file.

  • Code reusability – You can achieve code reusability by writing the code once and use it in different tests.
  • Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which makes it very easy to maintain code. Code changes happen only on Page Object Classes when a UI change occurs and enhances test maintenance and reduces code duplication.
  • Object Repository – Each page is defined as a java class and all the fields on the page will be defined in an interface as members, and the class will then implement the interface.
  • Readability – Due to a clear separation between test code and page-specific code, there is an enhancement in readability.

To read and write an excel file, the Apache POI library is capable to read write both xls and xlsx file format of excel.

Below are the steps to write to excel sheet -

  1. Create an xlsx file and save it at the desired location( d:testdata.xlsx). Add some data to read by selenium and rename sheet (ex. mysheet). 
  2. By default excel cell format is general, make it text.
  3. Close that excel file before the execution of the script.
  4. You need to download POI jars and unzip it. POI jars allow to create, modify, and display MS Office files using Java programs. Go to the official website of Apache POI download section http://poi.apache.org/download.html 
  5. In your editor Select Project
  6. Right-click on the project
  7. Go to build path
  8. Go to 'Configure build path;
  9. Click on the 'lib' tab and, 
  10. add POI external jar files.
  11. Below is the code to write excel file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
public class WriteExcel {
 public static void main(String []args){
  try {
  // To specify the file path which you want to create or write
  File src=new File("./test/testdata.xlsx");
  // To Load the file
  FileInputStream fis=new FileInputStream(src);
   // To load the workbook
   XSSFWorkbook wb=new XSSFWorkbook(fis);
  // To get the sheet to modify or create
   XSSFSheet sh1= wb.getSheetAt(0);
 // here createCell will create column and setCellvalue will set the value
 sh1.getRow(0).createCell(2).setCellValue("2.31.0");
 sh1.getRow(1).createCell(2).setCellValue("3.5");
 sh1.getRow(2).createCell(2).setCellValue("4.66");
// to specify where you want to save file
 FileOutputStream fout=new FileOutputStream(new File("location of file/filename.xlsx"));
// finally write content 
 wb.write(fout);
// close the file
 fout.close();
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
  }
 }

To read and write an excel file, the Apache POI library is capable to read and write both xls and xlsx file format of excel.

Below are the steps to write to excel sheet -

  1. Create an xlsx file and save it at the desired location( d:/test/testdata.xlsx). Add some data to read by selenium and rename sheet (ex. mysheet). 
  2. By default excel cell format is general, make it text.
  3. Close that excel file before the execution of the script.
  4. You need to download POI jars and unzip it. POI jars allow to create, modify, and display MS Office files using Java programs. Go to the official website of Apache POI download section http://poi.apache.org/download.html
  5. In your editor Select Project
  6. Right-click on the project
  7. Go to build path
  8. Go to 'Configure build path;
  9. Click on the 'lib' tab and, 
  10. add POI external jar files.
  11. Below is the code to read excel file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
 public class ReadExcel {
 public static void main(String []args){
  try {
  // To specify the path of file
  File src=new File("filepath/excelsheetname.xlsx");
   // To load file
   FileInputStream fis = new FileInputStream(src);
   // To load workbook
   XSSFWorkbook wb=new XSSFWorkbook(fis);
   // To load sheet- Here loading the first sheet
      XSSFSheet sh1= wb.getSheetAt(0);
  // getRow() to specify which row we want to read.
  // and getCell() to specify which column to read.
  // getStringCellValue() to specify that we are reading String data.
 System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
 System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());
 System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());
 System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());
 System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());
 System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());
  } catch (Exception e) {
   System.out.println(e.getMessage());
  }
  }
 }

A headless browser is a browser that does not have a GUI. It is used to simulate programs even though there is no browser installed on the local system. You will not see the browser in your system but will get the result in the console. The headless browser does not have GUI means program runs in the background without GUI.

Two headless browsers widely used are HtmlUnitDriver and PhantomJSDriver.

Advantages of performing Headless browser testing -

  1. It is faster. Compared to browser automation, performance is better. Running regression scripts using browser takes lots of time, but with headless browsers, time is saved.
  2. It allows you to run scripts on a system that does not have a browser.
  3. It helps in executing scripts on different browser versions on the local system even though that browser version is not available on the system. Most of the headless browsers support browser versions.

Disadvantages of Headless browsers testing -

  1. Debugging is difficult using headless browsers as the browser is not available. The only way is to capture a screenshot.

We know Selenium WebDriver is a tool to automate User Interface and We could only interact with Browser using Selenium WebDriver.

We may face a situation where we want to get the data from the database or to update or delete the data from the Database.  If we want to automate anything outside the browser, we need to use other tools to achieve the task. For Database connection and work on it, use JDBC  API Driver. 

JDBC API lets the user connect and interact with the Database and fetch the data based on the queries used in the automation script. JDBC is a SQL level API that allows executing SQL statements. It creates connectivity between Java Programming Language and the database.

To make a connection to the database the syntax is -

DriverManager.getConnection(URL, "userid", "password" )

where the user ID is the username in the database

Password of the configured user

URL format is 'jdbc:< dbtype>://ipaddress:portnumber/db_name'

<dbtype> is the driver for the database to be connected. 

Code to create a connection is -

Connection con = DriverManager.getConnection(dbUrl,username,password);

Code to load JDBC Driver -

Class.forName("com.mysql.jdbc.Driver");

Once connection is set, use Statement Object to send queries -

Statement stmt = con.createStatement();

Once the statement object is created use executeQuery method

stmt.executeQuery(select *  from employee;);

In selenium mostly we click on an element using click() method.

Many times web controls don’t react against selenium commands and we face issues with the Click() statement. To overcome such a situation, in selenium we use the JavaScriptExecutor interface.

JavaScriptExecutor executes Javascript using Selenium driver and provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

To execute JavaScript within the browser using the Selenium WebDriver script, writing a separate script is not required. Just use a predefined interface named ‘Java Script Executor’ and need to import the JavascriptExecutor package in the script.

Package:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.JavascriptExecutor;

Syntax:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);

where Script is the JavaScript to be executed.

Arguments are the arguments to the script and are optional and can be empty.

JavascriptExecutor returns either Boolean, or Long, or String, or List, or WebElement, or null.

Let us discuss some scenarios we could handle using JavascriptExecutor :

  1. Without using the sendKeys() method, you can use this interface to type Text in Selenium WebDriver.
  2. Using JavascriptExecutor, you can click on a Button.
  3. You can use it to handle the Checkboxes.
  4. It can be used to generate the Alert Pop window.
  5. You can Refresh browser window using Javascript
  6. You can get the inner text of the entire webpage in Selenium
  7. Get the Title of webpage
  8. Get the domain
  9. Get the URL of a webpage
  10. Perform Scroll on an application using Selenium
  11. Click on a SubMenu which is only visible on mouse hover on Menu
  12. Navigate to a different page using Javascript.

Using Selenium WebDriver, handling of AJAX calls is one of the common issues. Users will not be aware when the AJAX call would be completed and the page has been updated. 

AJAX stands for Asynchronous JavaScript and XML and AJAX allows the web page to retrieve small amounts of data from the server without reloading the entire page. From the client to server AJAX sends HTTP requests and then process the server’s response without reloading the entire page. Wait commands may not work to handle AJAX control in such a scenario and it is just because the actual page is not going to refresh.

For example, When you click on the submit button, the required information may appear on the web page without refreshing the browser or sometimes it may load in a second or sometimes it may take longer. And you do not have any control overloading time. The best way to handle this kind of situation in selenium is to use dynamic waits that are WebDriverWait in combination with ExpectedCondition.

Some of the methods available are as follows:

  1. titleIs() – titleIs() waits for a page to load with a specific title. wait.until(ExpectedConditions.titleIs(“Google”));
  2. elementToBeClickable() – elementToBeClickable() waits for an element to be clickable i.e. element should be present/displayed/visible on the screen as well as enabled.
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
  3. alertIsPresent() – alertIsPresent () waits for an alert box to appear.
    wait.until(ExpectedConditions.alertIsPresent()) !=null);
  4. textToBePresentInElement() – textToBePresentInElement() waits for an element having a certain string pattern.
    wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));

Selenium has the ability to handle various types of keyboard and mouse events. In order to perform action events, use org.openqa.selenium.interactions Actions in class. This API includes actions such as clicking multiple elements, drag and drop.

Let us create an object action of Action class

Actions action = new Actions(driver);

Now to focus on an element using WebDriver use action -

actions.moveToElement(element).perform();

Here perform() method is used to execute the action.

Let us see mouse events using selenium action class API -

  • click() : It Clicks on an element.
  • doubleClick() : Double clicks onElement.
  • contextClick() : Performs a context-click on an element. 
  • clickAndHold() : It Clicks on an element without releasing.
  • dragAndDrop(source, target) : Invokes click-and-hold at the location and moves to the target location of the element before releasing the mouse. where the source is an element to grab and the target is the element to release. 
  • dragAndDropBy(source, xOffset, yOffset) : Performs click-and-hold at the source location and shifts by a given offset, then frees the mouse. Here xOffset is to shift horizontally and yOffset is to shift vertically.
  • moveByOffset(x-offset, y-offset) : Shifts the mouse from its current position (or 0,0) by the given offset. 
  • moveToElement(toElement) : Shifts the mouse to the centre of the element. 
  • release() : Releases left mouse button at the existing mouse location

Both setSpeed() and sleep() will delay the speed of script execution.

Thread.sleep(): It will stop the current execution of script thread for a specified period of time. It is done only once and it takes a single argument in integer format

For example: thread.sleep(2000)- Execution of the script will be stopped for 2 seconds

It waits only once at the command given at sleep.

SetSpeed(): It will stop the execution of each and every selenium command for a specific amount of time and it takes a single argument in integer format

For example selenium.setSpeed(“2000”)- It will wait for 2 seconds for each and every command before the execution of the next command.

It runs each command after setSpeed delay by the number of milliseconds mentioned in set Speed.

Page Factory class in selenium is an extension of the Page object design pattern. 

Page Factory is an inbuilt concept that provides an optimized way to implement the Page Object Model. Here optimization is, it refers to the fact that the memory utilization is very good and also the implementation is done in an object-oriented manner.

It is used to initialize the elements on the Page Object or instantiate the Page Objects. Annotations for elements can be created and recommended as the describing properties may not always be descriptive enough to differentiate one object with the other.

Here the concept of separating the Page Object Repository and Test Methods is followed. Instead of using ‘FindElements’, here we use annotations like @FindBy to find WebElement, and the initElements method to initialize web elements from the Page Factory class. It makes handling "Page Objects" easier and optimized by providing the  @FindBy annotation and initElements method.

@FindBy annotation - can accept attributes tagName, partialLinkText, name, linkText, id, CSS, className & XPath and is used to locate and declare web elements using different locators.

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

initElements() - is a static method of PageFactory class used in conjunction with @FindBy annotation. Web elements located by @FindBy annotation can be initialized using the initElements method. 

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

Questions on the dropdown and selecting a value from the dropdown are common Selenium interview questions.

You should know that to work with a dropdown in Selenium, always make use of HTML tag: ‘select’. Without using ‘select’, you cannot handle dropdowns. 

So the steps to select an element from the drop-down are -

  1. Identify the ‘select’ HTML tag as dropdowns must have the ‘select’ tag)
  2. Select an option from that dropdown element

To identify the ‘select’ html element from the web page, use findElement() method. Look at the below piece of code:

WebElement mySelectElement = driver.findElement(By.id("id value"));

Select dropdown = new Select(mySelectElement);

Now to select an option from that dropdown can be done in three ways:

    dropdown.selectByVisibleText(“text1”); → Select an option by the visible text.

    dropdown.selectByIndex(“1”); → Select, by choosing the Index number of a option.

    dropdown.selectByValue(“value”); → Select by choosing the value.

These are the different ways to select a value from a dropdown.

There are different frameworks available in selenium, but below three frameworks are popular and you can create these three different types of frameworks using selenium are -

Data-Driven Framework:- Currently Data Driven Framework is one of the popular automation testing frameworks. 

The entire test data is generated from some external files like Excel, CSV, XML or some database table,  and it is called Data Driven framework. The data-driven test performs the same functionality with multiple input values.

Keyword Driven Framework:- Keyword driven framework is also known as Table driven testing or action word based testing.

When the instructions and operations are written in a different external file like an Excel worksheet, it is called Keyword Driven framework. It is used to speed up automation testing by using the keywords for a common set of actions.

Hybrid Framework:- It is a combination of both the Data-Driven framework and the Keyword Driven framework is called the Hybrid framework. Keywords are written in external files like excel file and code will call this file and execute test cases.

Advanced

Download and install AutoIt tool

Open SciTE Script editor and add the below mentioned AutoIt script. Save it as ‘UploadFile.au3’ in your system.

Below is the AutoIt Script:

WinWaitActive("File Upload") 
Send("D:\SoftwareTestingMaterial\UploadFile.txt") 
Send("{ENTER}")

Save it as ‘UploadFile.au3’

After the file is saved, we need to convert the ‘UploadFile.au3’ to ‘UploadFile.exe’. (This can be done by Right Click on the file and click on ‘Compile Script’) .

Add the below mentioned Selenium Script and run :

Runtime.getRuntime().exec(“D:\\Automation\\AutoIt\\Uploadfile.exe”);

The main difference between driver.findElement() and driver.findElements() commands is-

findElement() returns a single WebElement (which is found first) based on the locator passed as the parameter. Whereas findElements() returns a list of WebElements satisfying the locator value passed. It returns an empty list if there are no web elements matching the locator strategy.

Syntax of findElement()-

WebElement textbox = driver.findElement(By.id(“textBoxLocator”));

Syntax of findElements()-

List <WebElement> elements = element.findElements(By.id(“value”));

Another difference between the two is- if no element is found then findElement() throws NoSuchElementException whereas findElements() returns a list of 0 elements.

Page Object Model is an Object Repository design Pattern most commonly used in Selenium Test Automation. It is primarily used for enhancing test maintenance and reducing code duplication. Page object model (POM) can be used in any type of framework - modular, data-driven, hybrid framework or keyword driven, etc. A page object is an object-oriented class that serves as an interface to a page of the Application Under Test (AUT). The tests use these methods of page object class whenever they need to interact with the UI of that page. The benefit is that if there is a UI change, there is no need to change the tests only the code within the page object needs to be changed.

Page Factory in Selenium is an extension to Page Object Model and can be used to initialize web elements that are defined in web page classes or Page Objects.

Page Factory will initialize every WebElement variable with a reference to a corresponding element on the actual web page based on configured “locators”. This is done by using the annotation @FindBy. Example

@FindBy(xpath = "(//option[text()='Basic auth'])[2]")
private WebElement typeSctApp;

Desired Capabilities is used to set properties for the WebDriver. It is also used to set the properties of browser such as to set BrowserName, Platform, Version of Browser etc.

Example :

String baseUrl , nodeUrl;
baseUrl = "https:// https://www.seleniumhq.org/ ";
nodeUrl = "http://192.168.10.21:5568/wd/hub";
DesiredCapabilities dcap = DesiredCapabilities.firefox();
dcap.setBrowserName("firefox");
dcap.setPlatform(Platform.WIN10_1);
driver = new RemoteWebDriver(new URL(nodeUrl),dcap);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Selenese is the set of selenium commands which are used for running the tests

There are three types of Selenese :

Actions: These are commands used for performing the operations and interactions with the target elements and manipulate the state of the application

Assertions: These commands are used as checkpoints or verification points. It verifies the state of the application conforms to the expected state.

Accessors: These commands examine the state of the application and store the values in a variables

WebDriver is an Interface which is implemented by FirefoxDriver Class.

FirefoxDriver is a class. It implements all the methods of WebDriver interface.

It makes the reference of the interface and makes an object of FirefoxDriver so as to call implemented methods of WebDriver interface.

We declare the left-hand side variable as WebDriver and right-hand side to create an object for a particular type of the browser and assign it.

WebDriver driver = new FirefoxDriver();

When we use ALT/SHIFT/CONTROL keys, we hold onto those keys and click other buttons simultaneously to achieve the special functionality.

To  hold onto these keys while subsequent keys are pressed, you need to define two more methods: keyDown(modifier_key) and keyUp(modifier_key)


Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONTROL)

The purpose is to Perform a modifier key press and not to release the modifier key. Subsequent interactions may assume it’s kept pressed.

Parameters: Modifier_key (keys.ALT or Keys.SHIFT or Keys.CONTROL)

The purpose is to Perform a key release.

With a combination of these two methods, you can capture the special function of a particular key.

public static void main(String[] args) 
{
String baseUrl = “https://www.facebook.com”;
WebDriver driver = new FirefoxDriver();
driver.get("baseUrl");
WebElement txtUserName = driver.findElement(By.id(“Email”);
Actions builder = new Actions(driver);
Action seriesOfActions = builder
 .moveToElement(txtUserName)
 .click()
 .keyDown(txtUserName, Keys.SHIFT)
 .sendKeys(txtUserName, “hello”)
 .keyUp(txtUserName, Keys.SHIFT)
 .doubleClick(txtUserName);
 .contextClick();
 .build();
seriesOfActions.perform();
}

Selenium IDE has a built-in linguistic system called Selenese. Selenese is a collection of Selenium commands to perform actions on a web page.

Selenese can detect broken links on a page, or check the presence of a web element, Ajax, JavaScript alerts and a lot of many things. Mainly there are three types of command in Selenese. 

  1. Actions: Action can alter the state of an application. For example,  clicking on a link, or selecting a value from the drop-down, etc. Action command directly interacts with web elements.
  2. Accessors: Accessor commands monitor the state of an application and store it into some variable. For example, storeTextPresent, or storeElementPresent, etc are accessor commands because it reads the state of the element and stores it into a variable.
  3. Assertions: Assertion commands allow adding a checkpoint or a verification point. The assertion command confirms the current state of a UI element. These commands verify if a certain condition is met.

Selenium RC has a complex architecture whereas in WebDriver those complications are removed. Let us discuss why WebDriver is better than the RC.

Selenium RC is slow because it uses an additional JavaScript layer known as the core and On the other hand, WebDriver is fast as it natively speaks with the browser by utilizing browser's built-in engine to control it.

The selenium core can not ignore the disabled elements while WebDriver handles the page elements more realistic way.

Selenium RC has a more mature set of APIs but contains redundancies and complicated and confusing commands. Whereas, WebDriver APIs his simpler and have a cleaner interface and do not have redundant and confusing commands.

Selenium RC does not provide support headless HtmlUnit browser. It requires a real visible browser to operate on. On the other hand, WebDriver supports a headless HtmlUnit browser.

Selenium RC includes a test result generator for HTML reports. Whereas WebDriver does not have any built-in reporting ability.

For Mozilla’s Gecko engine, Marionette is the web automation driver. In the test automation developers community, it is also famous as the Gecko Driver. Marionette can control both the chrome i.e. menus and functions or the content of the webpage loaded inside the browsing context, giving a high level of control and ability to replicate user actions. Along with performing actions on the browser, Marionette can also read the properties and attributes of the DOM

It has two modules, first is the server that accepts requests and executes and the second is a client to forward commands to the server.

We use Marionette to run UI tests in the Firefox browser. A test automation engineer should add its dependencies to the framework, import the required classes and call the methods to control the web page. Marionette also returns the status of commands executed on the browser which can help in verifying the authenticity of the actions performed.

Selenium is a set of different software tools each with a different purpose and approach to supporting test automation. Selenium Webdriver is one of the tools in Selenium. The Java version of WebDriver supports the implementation of the Selenium-RC API. WebDriverBackedSelenium is a class name where you can create an object for it. The WebDriver API is fundamentally different in its design compared to Selenium RC. You can use the WebDriver technology using the Selenium-RC API. This is mainly provided for backward compatibility. WebDriverBacked selenium allows you to use existing Selenium RC test suites using Selenium-RC API to use WebDriver under the cover. WebDriverBackedSelenium allows you to create tests with Selenium Remote Control syntax.

String baseUrl = "https://nikasio.com";
String remoteControl = "localhost";
Int port = 4444;
String browser = "*firefox";
Selenium selenium = new DefaultSelenium(remoteControl, port ,browser ,baseUrl);
selenium.start();
selenium.open("/");
selenium.click("link=chapter1");
// rest of the test code
WebDriverBackedSelenium is a class name where we can create an object for it as below: Selenium WebDriver= new WebDriverBackedSelenium(WebDriver objectName, “URL path of website”).

The main purpose of this is when we want to write code using both WebDriver and selenium RC, we must use the above-created object to use selenium commands.

Many times test cases fail while running automated test scripts due to various reasons. It might be due to multiple reasons like network issues, system issues or browser issues, etc. and we need to execute test scripts again using TestNG in Selenium. We can test these failed cases in two ways:

Case 1: Execute failed test cases using TestNG in Selenium – By using “testng-failed.xml”

  1. After the first run of the automated test run, right-click on Project - Click on Refresh
  2. A folder will be generated named the “test-output” folder, and inside “test-output” folder, you can find “testng-failed.xml”
  3. Run “testng-failed.xml” to execute the failed test cases again.

Case 2: Execute failed test cases using TestNG in Selenium – By Implementing TestNG IRetryAnalyzer.

Create a class to implement IRetryAnalyzer. Here we create a class (say, RetryFailedTestCases) and implementing IRetryAnalyzer.

package runfailedtestcases;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
public class RetryFailedTestCases implements IRetryAnalyzer {
    private int retryCnt = 0;
    //You can ntioned maxRetryCnt (Maximiun Retry Count) as per your requirement. Here if any failed testcases then it runs two times
    private int maxRetryCnt = 2;
    //This method will be called every time a test fails and will return TRUE if a test fails and need to be retried, else it returns FALSE
    public boolean retry(ITestResult result) {
        if (retryCnt < maxRetryCnt) {
            System.out.println("Retrying " + result.getName() + " again and the count is " + (retryCnt+1));
            retryCnt++;
            return true;
        }
        return false;
    }
}

A simple implementation of this ‘IAnnotationTransformer’ interface can help you set the ‘setRetryAnalyzer’ for ‘ITestAnnotation’. Add the above class name (RetryFailedTestCases.class) in the below program.

package runfailedtestcases;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
public class RetryListenerClass implements IAnnotationTransformer {
 @Override
 public void transform(ITestAnnotation testannotation, Class testClass, Constructor testConstructor, Method testMethod) {
 IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
  if (retry == null) {
 testannotation.setRetryAnalyzer(RetryFailedTestCases.class);
 }
 }

We can evaluate the above example by simple tests

Testcase 1:

package runfailedtestcases;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Test1 {
 @Test
 public void test1(){
 System.out.println("Test 1");
 Assert.assertTrue(true);
 }
}

Testcase 2:

package runfailedtestcases;
import org.testng.Assert;
import org.testng.annotations.Test;
public class Test2 {
 @Test
 public void test2(){
 System.out.println("Test 2");
 Assert.assertTrue(false);
 }
}

As per the lines of code in Test2, it will fail. So Test2 will be executed 2 times as we took the maxRetryCnt as 2 in Retry Class. First, let us add the below-mentioned Listener to the testng.xml file. The below-mentioned syntax is to add Listener for RetryListnereClass subtext

<listeners>
        <listener class-name="softwareTestingMaterial.RetryListenerClass"/>
</listeners>
Final testng.xml will look like below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Suite">
<listeners>
        <listener class-name="softwareTestingMaterial.RetryListenerClass"/>
  </listeners>
 <test name="Test1">
 <classes>
 <class name="runfailedtestcases.Test1" />
 </classes>
 </test> <!-- Test -->
 <test name="Test2">
 <classes>
 <class name="runfailedtestcases.Test2" />
 </classes>
 </test> <!-- Test -->
</suite> <!-- Suite -->

After executing testng.xml the output shows Test 2 is executed 3 times as we have mentioned “maxRetryCnt=2”. Even though we have just 2 test cases, we could see total test runs are 4 in the result.

This way we could run failed test cases by applying TestNG in Selenium.

Tooltip is also known as the Help text. Tooltip is a text that appears when the mouse hovers over an object like a link, button image, etc. Sometimes it is a requirement of a project to address tooltip text. This tooltip text provides information related to the object on which it appears. Objects have various attributes in HTML i.e object properties and one of them is “title” which contains tooltip text. Selenium’s purpose is to read that text of the object. Tooltip can appear in two ways - Static and Dynamic ways and both can be seen by mouse hover on the object. 

1. Static Tooltip:

Selenium can capture the Static tooltip by calling getAttribute(‘title’) method of WebElement and return the text of title which will be nothing but the tooltip.

We will use the class attribute to make the image object(WebElement) and then we will use the getAttribute method.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class staticToolTip {
public static void main(String[] args) {
                //Keep the chromedriver at project path location in eclipse
System.setProperty("WebDriver.chrome.driver",
 System.getProperty("user.dir")+"/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://nikasio.com");
//Find the element by using class name
WebElement edit = driver.findElement(By.id("header_logo"));
String tooltiptext = edit.getAttribute("title");
System.out.println(tooltiptext);
driver.quit();
}
}

2. Dynamic Tooltip:

Dynamic Tooltip in applications is usually created by jQuery/javascript plugins. When we hover mouse on the object, tooltip object appears in HTML and as soon as the mouse is moved the object text disappears. The getAttribute(‘title’) will not simply work. In the case of Dynamic tooltip, you have to use the ‘Actions class’ of Selenium.

In the above image, you will see object related to this link but nothing for tooltip

Once you will hover the mouse over the link, you will see a new entry in HTML(div tag ) which is nothing but the tooltip and when you will take the mouse out of the link, below div tag will disappear.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class dynamictoolTip {
public static void main(String[] args) throws InterruptedException {
System.setProperty("WebDriver.chrome.driver", System.getProperty("user.dir")+"/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://nikasio.com");
//Create object for link
WebElement exampleLink = driver.findElement(By.class("avatar user-1-avatar avatar-150 photo"));
//Create the Actions class
Actions act = new Actions(driver);
act.moveToElement(exampleLink).build().perform();
//Create object for inner div 
WebElement toolTip = driver.findElement(By.className("header_logo"));
//Get the text of Tooltip
String tooltiptext = toolTip.getText();
System.out.println(tooltiptext);
driver.quit();
}
}

Selenium Webdriver is itself an API and it’s an interface. Selenium hierarchy contains two WebDriver - Remote WebDriver and Selenium WebDriver. Remote WebDriver is a class that implements the Selenium WebDriver interface whereas browser classes ChromeDriver(), FirefoxDriver() and etc. extend the Remote WebDriver. There are many APIs and methods in Selenium and following are some as follows:

 1. Navigation Commands:

a. navigate().to(URL) - To navigate to a particular URL.
Driver.navigate().to("http://qatechhub.com");

b. get(url) - To navigate to a particular URL.
Driver.get("http://qatechhub.com");

c. navigate().back() - Takes us  back in the browsing
Driver.navigate().back();

d. navigate().forward() - Takes us  forward in the browsing
Driver.navigate().forward();

e. navigate().refresh() - reloads the page.

Driver.navigate().refresh();

2. Resizing Windows:

Set Size - Sets the size of the window; the unit used is pixels.

Dimension d = new Dimension(640, 640);

Driver.manage().window().setSize(d);

Maximizing the Window - To set the size of the window as full size as per the screen.

Driver.manage().window().maximize();

3. Deleting Cookies:

Delete cookies in Selenium as per below command

Driver.manage().deleteAllCookies();

This will not actually delete the physical cookies file from the browser but it bypasses these files that cookies don’t appear in the browsing experience.

4. Closing the Browser:

close() - Closes the active window

Driver.close();

quit() - closes all the windows which are open in Selenium sessions

Driver.quit();

5. Different Get Methods:

a. getCurrentUrl() - This method returns the URL of the currently active page as a string.

b. getPageSource() - This method returns the complete HTML source code of the page.

c. getTitle() - This method returns the title of the current page as a string.

d. getWindowHandle() - This method returns the sessionId or windowHandle as a string.

e. getWindowHandles() - This method returns a set of sessionIds or windowHandles.

6. Searching WebElements: 

To search for web elements on a web page below methods are used:

a. findElement() - This method returns a web element that matches the required criteria.

    WebElement element = Driver.findElement(By.id("text-box"));

b. findElements() - This method returns a list of web elements which match the criteria.

    List<WebElement> allElements = Driver.findElements(By.id("checkbox"));

7. Mouse Operations:

Mouse operations like mouse hover, drag, and drop, right clickor double click with Selenium actions class is used:

Mouse Hover:      

Actions action = new Actions(Driver);

WebElement mobileElement = Driver.findElement(By.linkText("Mobile & Accessories"));

action.moveToElement(mobileElement).build().perform();

Drag and Drop:

WebElement source = Driver.findElement(By.id("draggable"));

WebElement target = Driver.findElement(By.id("droppable"));

Actions action = new Actions(Driver);

action.dragAndDrop(source, target).build().perform();

We can configure our WebDriver test or WebDriver test suites for software testing project in testng.xml file. If we have two/multiple classes in test suite we can run those classes in the same test as well as two different tests too. Let's take a simple example here:

Create 3 classes under project = TestNGOne and package = TestNGOnePack as below.

BaseClassOne will be used for initializing and closing WebDriver instance,

ClassOne and ClassTwo will be used as test classes.

  1. BaseClassOne.java:
package TestNGOnePack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
public class BaseClassOne {
    //Declared as public static to use same WebDriver instance publicly
    public static WebDriver driver = null;
    //@BeforeSuite annotation describes this method has to run before all suites
    @BeforeSuite 
    public void setup() throws Exception { 
         System.setProperty("WebDriver.gecko.driver", "D:\geckodriver.exe");
  driver = new FirefoxDriver();
         driver.manage().window().maximize();
         driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
         driver.get("https://nikasio.com"); 
    } 
    //@AfterSuite annotation - this method has to run after execution of all suites
    @AfterSuite
         public void tearDown() throws Exception { 
         driver.quit(); 
    } 
}

The above class will be base class and be used to initialize and close the WebDriver instance. 

  1. ClassOne.java:
package TestNGOnePack;
import org.testng.annotations.Test;
public class ClassOne extends TestNGOnePack.BaseClassOne{
 //@Test annotation - this method as a test method
 @Test
  public void testmethodone() {
    String title = driver.getTitle();
    System.out.print("nCurrent page title is : "+title);
    String Workdir = System.getProperty("user.dir");
    String Classpackname = this.getClass().getName();
    System.out.print("n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been executed successfully");
  }
}

Above ClassOne is inherited or created from BaseClassOne.

  1. ClassTwo.java:
package TestNGOnePack;
import org.testng.annotations.Test;
public class ClassTwo extends TestNGOnePack.BaseClassOne{
 //@Test annotation describes this method as a test method
 @Test
  public void testmethodone() {
  driver.navigate().to("http://facebook.com");
  String title = driver.getTitle();
  System.out.print("nCurrent page title is : "+title);
  String Workdir = System.getProperty("user.dir");
  String Classpackname = this.getClass().getName();
  System.out.print("n'"+Workdir+" -> "+Classpackname+" -> testmethodone' has been executed successfully");
  }
}

Above ClassTwo is also inherited or created from BaseClassOne.

Configure testng.xml to run two classes in one test:

Copy the below-given lines in the testng.xml file and run it as TestNg Suite.

<suite name="Suite One" >
 <test name="Test One" >
  <classes>
   <class name="TestNGOnePack.ClassOne" />
   <class name="TestNGOnePack.ClassTwo" /> 
  </classes>
 </test> 
</suite>

When execution is completed, View execution results report.

Configure testng.xml to run two classes in two tests:

Now if we want to run both classes as separate test then we have to configure testng.xml file as below

<suite name="Suite One" >
 <test name="Test One" >
  <classes>
   <class name="TestNGOnePack.ClassOne" />  
  </classes>
 </test> 
 <test name="Test Two" >
  <classes>
   <class name="TestNGOnePack.ClassTwo" /> 
  </classes>
 </test> 
</suite>

Here, "ClassOne" is included in 'Test One" test and "ClassTwo" is included in 'Test Two" test. Now run below given testng.xml file and verify results.

After comparing both results. In the 1st example, Both classes are executed under the same test but in the second example, both classes are executed under separate tests. This way you can configure the testng.xml file as per your requirement.

Many web browsers are available and used nowadays. Users may use FireFox, or Safari, or Chrome, or Internet Explorer browser for reading. Users may use different versions of the browsers and also may be running browsers on any OS like Windows, or Mac, or Linux.

To help users get the best user experience, you need to go extra miles and test Web application on different browsers along with different platforms. You need to test applications on different browsers and OS. You need to put extra effort and spend time testing your web application on every possible OS and available browser. Is it possible and feasible? Now how to make it possible? Here Selenium grid fits well and saves your time and energy.

Now the question is, Is it possible to set up selenium grid infrastructure using local systems? It is challenging to maintain Selenium Grid with all required browsers and operating systems and for that multiple online platforms provide an online Selenium Grid which you can access to run selenium scripts.

One of the important tools in the Selenium suite is Selenium Grid. Selenium grid has the capability of co-ordinating WebDriver tests or RC tests that can run on multiple browsers simultaneously. Selenium Grid can initiate WebDriver tests or RC tests on different operating systems. Selenium Grid even initiates or executes tests hosted on different machines. There can be only one hub and it will be a central part of the Selenium Grid setup and nodes are test machines on which tests are run.

Selenium Grid

Let us see how it works? Grid hosts a Hub-Node architecture. Here there is one Hub acts as the master and one or more nodes that act as slaves.

Consider you have 100 tests that are required to be executed simultaneously on different machines in different combinations of operating systems and browsers. Each machine has a different OS and inside OS, the test is executed on different browsers. This will save a lot of your execution time.

We know Selenium Grid is one of the important tools of Selenium suite and it functions on Node and multiple hub basis. Let us see what is Hub and Node? and how it works?

The Hub - There is only one Hub called as master and that is a central point of that grid setup. Any grid setup will have only one Hub. Tests that need to be executed should be loaded on HUB. Tests that are loaded on Hub will be executed only on Nodes. Any host machine can be configured as Hub and will co-ordinated test execution on other hosts.

The Nodes - Nodes are the machines on which tests are run. Hub will launch these tests. The Hub can launch one or more Nodes on remote machines or on the same machine where Hub is located. Each node can have different operating systems and different versions of the same browser or different browsers.

You need to configure Hub first and the register nodes with Hub to execute tests.

Before proceeding further with configuration make sure Java is installed on your system and environment variable is set. Now to configure Hub, first, you need to download the Selenium Server Jar file 'selenium-server-standalone-3.141.59.jar' from Seleniumhq's website.

Place this Jar file in an appropriate directory (says c:/Selenium Server. )

Open windows command prompt and navigate to the directory where Jar file is stored.

for example c:>Selenium Server

Now execute below command -

java -jar selenium-server-standalone-3.141.59.jar -role hub

Where selenium-server-standalone-3.141.59.jar is the downloaded jar file. -role flag is used to set a host machine as Hub.

One thing to keep in mind is Hub will be up and running as long as the command prompt is open. By default, the selenium grid uses 4444 port for web interfaces.

To check whether the Hub is up and running open browser and navigate to http://localhost:4444 and you will see below UI.

Nodes are host machines on which the tests are run. These tests are launched by the Hub. Hub can launch one or more nodes on remote machines or on the same machine where Hub is located. Node executes tests you loaded on the hub.

To configure nodes, you need to download the Jar files on the Node machines and place it on any directory of convenience. Open windows command prompt and execute below command-

java -DWebDriver.chrome.driver=C:chromedriver.exe -jar selenium-server-standalone-3.141.59.jar -role node -hub http://192.168.2.11:4444/grid/register

To set a Node on the same machine as you Hub, you need to open another command prompt other than Hub prompt.

-DWebDriver.chrome.driver=C:chromedriver.exe is used to set the browser driver path. 

-role node flag used to set a particular host machine as a node.

-hub http://192.168.2.11:4444/grid/register directs Node to connect with Hub using Hub's IP address. If you want to launch a Node on the same machine as your HUb, then you can specify ‘-hub http://localhost:4444/grid/register‘ in the command.

To check Nodes are registered, open and browser and navigate to http://localhost:4444/grid/console

Once Selenium Grid is configured, you can proceed with the test script execution on Nodes.

To execute scripts two important library packages DesiredCapabilities object and RemoteWebDriver object are required. DesiredCapabilities library is used to set browser type and the OS of Node. Use the below code to import the DesiredCapabilities object.

import org.openqa.selenium.remote.DesiredCapabilities;

The RemoteWebDriver object is used to select the Node on which test will be executed. Use the below code to import RemoteWebDriver object.

import java.net.MalformedURLException;

import java.net.URL;

import org.openqa.selenium.remote.RemoteWebDriver;

You can mouse hover on the logos of browser present in the Selenium Hub console to get the details like browserName and platform of the Node.

Use below code to setup grid

package TestGrid;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Assert;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class TestGrid {
 static WebDriver driver;
 static String nodeUrl;
 @BeforeTest
 public void setup() throws MalformedURLException {
 nodeUrl = "http://192.168.2.11:4444/wd/hub";
 DesiredCapabilities capabilities = DesiredCapabilities.chrome();
 capabilities.setBrowserName("chrome");
 capabilities.setPlatform(Platform.WINDOWS);
 driver = new RemoteWebDriver(new URL(nodeUrl), capabilities);
 }
 @Test
 public void simpleTest() {
 driver.get("https://nikasio.com");
 }
 @AfterTest
 public void afterTest() {
 driver.quit();
 }
}

Here the test is divided into three test annotations @BeforeTest, @Test, and @AfterTest. In @BeforeTest, DesiredCapabilities and RemoteWebDriver objects are used to configure Node. In @Test directed Node to navigate to nikasio.com's home page.In @AfterTest, directed Node to quite the browser instance.

On execution, you will get below output.

May 18, 2018 4:15:07 PM org.openqa.selenium.remote.ProtocolHandshake createSession

INFO: Detected dialect: OSS

PASSED: simpleTest

Every website is comprised of n number of technologies that are used in the backend and frontend. Three major technologies used for the front end and in the rendering are HTML5, CSS3, and JavaScript.

Every browser has a different rendering engine to compute these three technologies. Chrome uses Blink, Firefox uses Gecko and IE uses edge HTML and Charka. Because of these rendering engines, the same website renders complete differently in all these different browsers and that is the reason why you need cross-browser testing. To ensure the website works fine and functions the same across different browser versions and on different operating systems, cross-browser testing is required.

Reasons for why cross-browser testing is required are -

  1. To ensure browser compatibility with different operating systems.
  2. To ensure image orientation on different browsers.
  3. Different orientation of Javascript on each browser can cause an issue.
  4. To check font size mismatch or font not rendered properly.
  5. To check compatibility with the new web framework.

Selenium does not support report generation and test case management, we use the TestNG framework with selenium to support these features. TestNG is more advanced than JUnit and implementation of annotations is easy. 

The test suite is not defined in testing source code and it is represented in an XML file because the suite is a collection of test cases and an execution is the feature of the test suite.

To execute test cases in a suite or group of test cases, you need to create a testng.xml file. The testng.xml file contains the name of all classes and methods that needs to be executed as a part of execution flow.

Advantages of using testng.xml file are -

  1. The execution of multiple test cases from multiple classes is allowed.
  2. Parallel execution is allowed.
  3. Execution of test cases in groups, where a single test can belong to multiple groups is allowed.

We always wish to test our software using different sets of data to make sure software works properly under a different set of data.

Parameterization is the technique used to define values in the testng.xml file and send these values as parameters to the test case. Parameterization is useful when you want to pass multiple data to different test environments. We need to pass multiple data to the application at runtime. Below is the code in which empName is annotated as a parameter

public class ParameterizedTest1{
 @Test
 @Parameters("empName")
 public void parameterTest(String myName) {
 System.out.println("Parameterized value is : " + myName);
 }
}

To pass the parameter value using testng.xml, use the 'parameters' tag. Look at the below code -

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
 <suite name=”CustomSuite">
  <test name=”CustomTest”> 
   <parameter name="empName" value=”Donald"/>
    <classes>
     <class name="ParameterizedTest1" />
    </classes> 
  </test>
 </suite>

Maven builds the code and manages dependencies on the fly. Also due to its ability for supporting deployments Maven is used wide-spread. Maven makes a lot of post-development tasks easy. There are a bunch of other tools you can use instead of Maven.

Ant - Ant (Another Neat Tool) is a command-line tool written in Java and uses XML to build modules, define targets and specify dependencies.

IVY - IVY is a build tool from Apache and is an extension to Ant. IVY helps in managing the external dependencies during development. IVY provides a way of adding dependencies to the classpath and packaging them with the application. IVY is a lightweight alternative to Maven.

Gradle - Gradle an open-source build tool automates the build process taking over Ant and Maven tools. Gradel uses domain-specific language instead of XML templates for defining the project configuration. The groovy syntax is followed in a domain-specific language.

Gradel suggests a polyglot build system that integrates the project with different technologies and programming languages. Gradle makes version management easier than Maven with the help of dynamic versioning.

The two most commonly used network protocols are HTTP and HTTPS. There are multiple ways to handle both protocols in Selenium.

HTTP protocol -

No Authentication - When a website is using HTTP protocol and does not require any authentication, it is easy to handle

WebDriver driver = new ChromeDriver();

driver.get("http://destination-url/");

Basic authentication - Many websites apply basic authentication scheme before allowing access to the home page. You can handle basic authentication in three ways-

i) Using WebDriverWait and Alert classes to implement basic authentication for HTTP.

WebDriverWait testwait = new WebDriverWait(driver, 10); 
Alert testalert = testwait.until(ExpectedConditions.alertIsPresent()); 
testalert.authenticateUsing(new UserAndPassword(**user**, **pass**));

ii) pass user/pass pair within the HTTP URL as a parameter to WebDriver's Get method.

String target = “http://user:pass@host”;
public void login(String username, String password){
    WebDriver driver = new ChromeDriver();
    String URL = "http:// + username + ":" + password + "@" + "website link";
    driver.get(URL);
    driver.manage().window().maximize();
}

iii) Setting up browser preferences using the Selenium's profile classes.

FirefoxProfile FF = new FirefoxProfile();
FF.setPreference("network.http.phishy-userpass-length", 255);
driver = new FirefoxDriver(FF);
driver.get("http://user:pass@www.targetsite.com/");

HTTPS protocol - HTTPS is a secured protocol of HTTP and it encrypts communication exchanged between the web server and the browser. HTTPS protocol uses an SSL certificate that downloads onto the browser on initiating the first request. SSL certificate has a public key for encrypting the data transfer from client to server.

In short, we need to handle the SSL certificates in Selenium. To manage SSL in different browsers you need to use different approaches.

Handle SSL in Firefox - In firefox SSL is enabled using Selenium Profile APIs.

First load the profile of running browser instance.

ProfilesIni pf = new ProfilesIni();
FirefoxProfile ff = pf.getProfile ("myProfile");

Set the following properties to avoid security exception while opening the HTTPS site 

ff.setAcceptUntrustedCertificates(true);
ff.setAssumeUntrustedCertificateIssuer(false);

Now create Firefox driver instance using profile object.

WebDriver driver = new FirefoxDriver (ffProfile);

Handle SSL in Chrome - Chrome need to set SSL options via desired capabilities of selenium WebDriver.

First prepare DesiredCapabilities instance

DesiredCapabilities set_ssl = DesiredCapabilities.chrome();
set_ssl.setCapability (CapabilityType.ACCEPT_SSL_CERTS, true);
WebDriver driver = new ChromeDriver (set_ssl);

Handle SSL in IE - In IE SSL is managed with two different methods.

i) Native JavaScript code -

driver.navigate ().to ("javascript:document.getElementById('overridelink').click()");
ii) DesiredCapabilities Class -

DesiredCapabilities ssl = new DesiredCapabilities();
ssl.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
System.setProperty("WebDriver.ie.driver","IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver(ssl);

Continuous Integration is a technique which regulates the development process by automating the build and testing code on every commit made to the version control. Continuous Integration makes sure that new changes do not have any adverse effect on the build and existing functionality is not affected. In the case of a failed scenario, everyone including the one responsible for the changes will know about the failure without delay. With this timely reporting, developers find fair time to fix the issues and get prompt feedback.

Continuous Integration encourages best practices amongst developers by allowing them to merge their changes with other's code before checking into a shared repository. On time code integration eliminates changes of conflicts, duplication of functionality.

CI suggests using a version control system that supports Git workflows for intelligent branching. CI proposes having the main branch that keeps the stable code that can be used to deliver build at any time. At the same time developer can create transient features branches to start his work without interrupting others. Developers need to sync his code with Main Branch at regular intervals. On feature-complete, a developer should merge his code into the main branch after verification

In some automation scripts, there is a need to use mouse or keyboard actions to interact with OS like Alerts, download pop-up, Print pop-up, etc. and Selenium Webdriver cannot handle these OS pop-ups or applications.

A Robot is a class in Selenium and is used to generate native system input events for test automation, where you need control over the mouse and keyboard. To handle the OS popups which WebDriver does not handle, the Robot class was introduced.

The main purpose of ow Robot class is to assist automation testing for Java platform implementations. In other words, the Robot class provides control over mouse and keyboard devices.

This class is easy to implement and easily integrate with the automation framework.

Let us see the importance of the Robot class -

  1. Using Robot class you can easily upload a file
  2. Robot class handle the mouse and keyboard functions
  3. pop-ups can be handled easily with Robot class

Below are the few methods that help in the easy execution of test scripts required for Robot class implementation.

  1. KeyPress()
  2. KeyRelease()
  3. MouseMove()
  4. MousePress()
  5. MouseRelease()

Let us understand these methods in details -

  1. KeyPress() - Use this method when you want to press any key

Example : robot.keyPress(keyEvent.VK_UP); will press UP key on the keyboard.

  1. KeyRelease() - Use this method to release the pressed key on the keyboard.

Example: robot.keyRelease(keyEvent.VK_CAPS_LOCK); will release the pressed caps lock key on the keyboard.

  1. MouseMove() - use this method when you want to move the mouse pointer in the X and Y coordinates.

Example : robot.mouseMove(coordinates.get.X(),coordinates.get.Y());will move the mouse over X and Y coordinates.

  1. MousePress() - use this method to press the left button of the mouse.

Example - robot.mousePress(InputEvent.BUTTON1_MASK); will press the mouse button

  1. MouseRelease() - Help this method in releasing the pressed button of the mouse.

Example - robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); will release the right click of the mouse.

Let us see the code on how to declare robot class -

Robot robot = new Robot();

robot.keyPress(KeyEvent.VK_DOWN); //will press down key on the keyboard

robot.keyPress(KeyEvent.VK_TAB); // will press tab key on the keyboar

Description

Today Selenium has become one of the most popularly used open source Web UI (User Interface) automation testing suite developed by Jason Huggins in 2004. Selenium was invented with the introduction of a basic tool called “JavaScriptTestRunner”. It will support automation across different browsers, programming languages, and different platforms. Selenium can be easily developed on platforms like Linux, Solaris, especially Windows and Macintosh. 

Selenium can be defined as an open source automation tool that can be used to test the online browser applications. It has gained more popularity among developers and software testers as an open source portable automation testing framework. Today Selenium is used by many major online enterprises for testing their web interfaces including Google and Facebook.

Software testing has become the most significant and market-oriented job profile. People opting Quality Assurance Engineer or Quality analyst as a career are required to find out bugs or errors in the developed software and get them fixed in order to enhance the quality. Using Selenium framework, the user can reach the goal easily without spending much time and effort. If you are willing to take up Selenium testing as a professional, then it’s the right time to do it. 

As per the Payscale, the average pay for a Selenium Tester is $49.43 per hour. Quality Assurance Engineer or Quality analyst have an excellent opportunity to enhance their career in the steadily booming field of testing. In the current market scenario, there are huge opportunities available for a Quality Assurance Engineer or Quality analyst. Most of the companies are looking to hire people with testing knowledge.

Just a little preparation will make a job interview feel much less stressful.  The more time you take in advance to get ready, the more comfortable you'll feel during the actual interview. Our Selenium Interview Questions & Answers have been designed specially to get you familiarized with the nature of questions you might come across in your next Quality assurance engineer or a Quality analyst interview. Selenium coding interview questions and answers for freshers as well as for experienced will act as an advantage to crack your interview. The advance Selenium testing interview questions & answers you have learned so far will definitely help you to understand the selenium concepts clearly. These Selenium real-time basic interview questions and answers will surely boost your confidence to face an interview and will definitely prepare you to answer the toughest of Selenium interview questions in the best way possible. These Selenium framework real-time basic interview questions and answers are suggested by experts and have proven to have great value.

We hope these Selenium tricky interview questions and answers helped you understand the concepts of Selenium and will definitely help you to acquire the job.

The training provided by experienced and certified instructors will also help you understand the basic and advanced concept of the Selenium Automation Testing tool.

Wish you all the luck and confidence.

Read More
Levels