Вы находитесь на странице: 1из 12

Selenium Interview Questions

1. When did u use selenium Grid?

We used Selenium Grid to execute same or different test scripts on


multiple platforms and browsers concurrently so as to achieve distributed
test execution.

Advantages:

 It allows running test cases in parallel thereby saving test execution


time.
 It allows multi-browser testing
 It allows us to execute test cases on multi-platform

2. What is an XPath?

XPath is used to locate the elements. Using XPath, we could navigate


through elements and attributes in an XML document to locate web
elements such as textbox, button, checkbox, Image etc., in a web page.

findElement(By.xpath(“Xpath”));

1. Using single slash (Absolute Xpath):

html/body/div[1]/div[2]/div[2]/div[1]/form/div[1]/div/div[1]/div/div/in
put[1]

Single slash is used to create XPath with absolute path i.e. the XPath
would be created to start selection from the document node/start
node/parent node.

2. Double Slash:

Double slash is used to create XPath with relative path i.e. the XPath
would be created to start selection from anywhere within the
document. – Search in a whole page (DOM) for the preceding string.

Syntax: //form/div[1]/div/div[1]/div/div/input[1]

3. Single Attribute:

You could write the syntax in two ways as mentioned below. Including
or excluding HTML Tag. If you want to exclude HTML Tag then you
need to use *

//<HTML tag>[@attribute_name='attribute_value']
Selenium Interview Questions

or
//*[@attribute_name='attribute_value']

4. contains():
It is used to identify an element, when we are familiar with some part
of the attributes value of an element.

//<HTML tag>[contains(@attribute_name,'attribute_value')]

or

//*[contains(@attribute_name,'attribute_value')]

3. What is the difference between “/” and “//”

Single Slash “/” – Single slash is used to create XPath with absolute path
i.e. the XPath would be created to start selection from the document
node/start node.

Double Slash “//” – Double slash is used to create XPath with relative path
i.e. the XPath would be created to start selection from anywhere within the
document.

4. What is the difference between Absolute Path and Relative Path?

Absolute XPath starts from the root node and ends with desired
descendant element’s node. It starts with top HTML node and ends with
input node. It starts with a single forward slash(/) as shown below.

Syntax: /html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input

Relative XPath starts from any node in between the HTML page to the
current element’s node(last node of the element). It starts with a double
forward slash(//)

Syntax: //input[@id='email']

5. What is the difference between Assert and Verify in Selenium?

Assert:

When an “assert” command fails, the test execution will be aborted. So when
the Assertion fails, all the test steps after that line of code are skipped. The
Selenium Interview Questions

solution to overcoming this issue is to use a try-catch block. We use the


Assertion in the try catch block. Mostly, the assert command is used when
the end result of the check value should pass to continue to the next step.

In simple words, if the assert condition is true then the program control will
execute the next test step but if the condition is false, the execution will stop
and further test step will not be executed.

Assert. AssertEquals (true, false);

Verify:

When a “verify” command fails, the test will continue executing and logging
the failure. Mostly, the Verify command is used to check non-critical things.
In such cases where we move forward even though the end result of the
check value is failed.

In simple words, there won’t be any halt in the test execution even though
the verify condition is true or false.

In TestNG, we use only Assert Statements. We can use Verify statement in


terms of if-else and try-catch.

if(isElementPresent(By.linkText("login"))){
System.out.println("Login link is present");
} else{
System.out.println("Login link is not present");
}

(OR)

try {
assertTrue(isElementPresent(By.xpath("assert-and-verify")));
} catch (Error e) {
verificationErrors.append(e.toString());
}

6. How to take screen shots for Failed Test Cases


Why screenshot is required in automation?

It helps us to understand the flow of application whether application is


behaving correctly or not.
It is used mostly in cross browser testing
Screenshot on failure.
Selenium Interview Questions

package softwareTestingMaterial;

import java.io.File;

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.Test;

public class CaptureScreenshot {

@Test

public static void captureScreenMethod() throws Exception{

WebDriver driver = new FirefoxDriver();

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

try{

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

driver.navigate().refresh();

//driver.findElement(By.xpath("//*[@id='cse-search-

box']/div/input[4]")).sendKeys("agile"); //Statement with correct Xpath

driver.findElement(By.xpath("//*[@id='cse']")).sendKeys("agile");

//Statement with incorrect Xpath

}catch(Exception e){

TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
Selenium Interview Questions

Files.copy(source, new File("./Screenshots/facebook.png"));

driver.close();

driver.quit();

7. What are the types of waits available in Selenium WebDriver?

There are three Implicit Wait

a. Implicit Wait:

Implicit waits tell to the WebDriver to wait for a certain amount of time
before it throws an exception. Once we set the time, WebDriver will
wait for the element based on the time we set before it throws an
exception. The default setting is 0 (zero). We need to set some wait
time to make WebDriver to wait for the required time.

Syntax:

driver.manage().timeouts().implicitlyWait(TimeOut,TimeUnit.SECONDS)

Implicit Wait time is applied to all the elements in the script.

b. Explicit Wait:

Explicit waits are confined to a particular web element. Explicit Wait is


code you define to wait for a certain condition to occur before proceeding
further in the code.

a. Web driver wait


b. Fluent wait

Web driver wait:

It is applied on certain element with defined expected condition and time. This wait is
only applied to the specified element. This wait can also throw exception when
element is not found
Selenium Interview Questions

driver.manage().timeouts().Explicity(TimeOut,TimeUnit.SECONDS)

8. How to input text in the text box using Selenium WebDriver?

By using SendKeys ();


9. click on a hyperlink:

driver.findElement(By.linkText(“Software Testing Material Website”)).click();

10. fetch the current page URL

driver.getCurrentUrl();

11. What is the difference between driver.close() and


driver.quit() methods?

driver.close(): To close current WebDriver instance


driver.quit(): To close all the opened WebDriver instances

12. What is the difference between driver.findElement() and


driver.findElements() commands?

a. findElement() returns a single WebElement (found first) based on the


locator passed as parameter.
if no element is found then findElement() throws NoSuchElementException

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

b. findElements() returns a list of WebElements, all satisfying the locator


value passed.
findElements() returns a list of 0 elements.
List <WebElement> elements = element.findElements(By.id(“value”));

13. How to find whether an element is displayed on the web page?

WebDriver facilitates the user with the following methods to check the visibility of
the web elements. These web elements can be buttons, drop boxes, checkboxes,
radio buttons, labels etc.

a. isDisplayed():

boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();


Selenium Interview Questions

b. isSelected():

boolean selected = driver.findElement(By.xpath("xpath")).isSelected();

c. isEnabled():

boolean Enabled = driver.findElement(By.xpath("xpath")).isEnabled();

14.how to select a value in DropDown()?

By using Select Class

WebElement mySelectElement = driver.findElement(By.name("dropdown"));


Select dropdown = new Select(mySelectElement);
dropdown.selectByVisibleText(Text);
dropdown.selectByIndex(Index);
dropdown.selectByValue(Value);

15. How to mouse hover on a web element using WebDriver?

WebElement ele = driver.findElement(By.xpath("xpath"));


//Create object 'action' of an Actions class
Actions action = new Actions(driver);
//Mouseover on an element
//action.moveToElement(ele).perform();

actions. MoveToElement(driver.findElement(By.Xpath(“”))).build().Perform();

16.How To Handle Javascript Alerts/PopUps In Selenium WebDriver

To handle alerts popups we need to do switch to the alert window and call Selenium
WebDriver Alert API methods.

There are two types of alerts.

1. Windows Based
2. Web Based/Browser Based

To handle Browser based Alerts (Web based alert popups), we


use Alert Interface. The Alert Interface provides some methods to handle the
popups.

In order to switch the control to alert pop up, we use the following command :

driver.switchTo().alert();

Let’s see the Alert Interface Methods.


Selenium Interview Questions

We need to Import a package org.openqa.selenium.Alert to handle the alerts in


Selenium.

To get a handle to the open alert:

Alert alert = driver.switchTo().alert();

To Click on OK button:

alert.accept();

To click on Cancel button.

alert.dismiss()

To get the text which is present on the Alert.

alert.getText();

To enter the text into the alert box


alert.sendkeys(String stringToSend);

To Authenticate by passing the credentials

alert.authenticateUsing(Credentials credentials)

17. How to read a JavaScript variable in Selenium WebDriver?

By using JavascriptExecutor

// To initialize the JS object.


JavascriptExecutor JS = (JavascriptExecutor) webdriver;
// To get the site title.
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

18.How do you read test data from excels?

Test data can efficiently be read from excel using JXL or POI API

Apache POI is an open source library developed and distributed by Apache


Software Foundation to design or modify Microsoft Office files using Java
program. It is a popular API that allows to work around excel files using Java
Programs. In short, you can read and write MS Excel files using Java. Apache
POI is your Java Excel solution.
You’d use HSSF if you needed to read or write an Excel file using Java (XLS).
Selenium Interview Questions

You’d use XSSF if you need to read or write an OOXML Excel file using Java
(XLSX). It has many predefined methods, classes, and interfaces.

List of different Java Interfaces and classes in POI for

reading XLS and XLSX file

Workbook: HSSFWorkbook and XSSFWorkbook classes implement this interface


HSSFWorkbook: It is a class represents XLS file
XSSFWorkbook: It is a class represents XLSX file
Sheet: HSSFWorkbook and XSSFWorkbook classes implement this interface
HSSFSheet: It is a class represents a sheet in a XLS file
XSSFSheet: It is a class represents a sheet in a XLSX file
Row: HSSFWorkbook and XSSFWorkbook classes implement this interface
HSSFRow: It is a class represents a row in a sheet of XLS file
XSSFRow: It is a class represents a row in a sheet of XLSX file
Cell: HSSFWorkbook and XSSFWorkbook classes implement this interface
HSSFCell: It is a class represents a cell in a row of XLS file
XSSFCell: It is a class represents a cell in a row of XLSX file

How to read excel file using apache POI


//How to read excel files using Apache POI
public class ReadExcel {
public static void main (String [] args) throws IOException{
//I have placed an excel file 'Test.xlsx' in my D Driver
FileInputStream fis = new FileInputStream("D:\\Test.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
//I have added test data in the cell A1 as "SoftwareTestingMaterial.com"
//Cell A1 = row 0 and column 0. It reads first row as 0 and
Column A as 0
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
System.out.println(cell);
System.out.println(sheet.getRow(0).getCell(0));
Selenium Interview Questions

//String cellval = cell.getStringCellValue();


//System.out.println(cellval);

}
}

How to write Excel using Apache POI:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteExcel {

public static void main (String [] args) throws IOException{


//create an object of Workbook and pass the FileInputStream object into it to
create a pipeline between the sheet and eclipse.
FileInputStream fis = new FileInputStream("D:\\Test.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
//call the getSheet() method of Workbook and pass the Sheet Name here.
//In this case I have given the sheet name as “TestData”
//or if you use the method getSheetAt(), you can pass sheet number
starting from 0. Index starts with 0.
XSSFSheet sheet = workbook.getSheet("TestData");
//XSSFSheet sheet = workbook.getSheetAt(0);
//Now create a row number and a cell where we want to enter a value.
//Here im about to write my test data in the cell B2. It reads Column B as 1 and
Row 2 as 1. Column and Row values start from 0.
//The below line of code will search for row number 2 and column number 2
(i.e., B) and will create a space.
//The createCell() method is present inside Row class.
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
//Now we need to find out the type of the value we want to enter.
//If it is a string, we need to set the cell type as string
//if it is numeric, we need to set the cell type as number
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue("SoftwareTestingMaterial.com");
FileOutputStream fos = new FileOutputStream("D:\\Test.xlsx");
workbook.write(fos);
fos.close();
System.out.println("END OF WRITING DATA IN EXCEL");
}
}
Selenium Interview Questions

19. Is it possible to automate the captcha using Selenium?

No, It’s not possible to automate captcha and bar code reader.

20.How to switch between frames in selenium?

driver.switchTo().frame();

21.Scroll Web Page Down Or UP

JavaScript scrollBy() method

22. To Perform Drag And Drop Action

By using Action class

23.To Highlight Element Using Selenium WebDriver?

using JavascriptExecutor interface,

24.Have you used any crossbrowsertesting tool to run selenium scripts on


cloud?
I have used BrowserStack to run selenium tests on multiple browsers & Multiple
operating systems in parallel.

25. Read the test data from the Excel cell, in this we are passing parameters as Row num and
Col num

public static string getCellData(int rownum, int colnum) throws exception

Try{

Cell =excelwsheet.getrow(rowno).getcell(cellNo);

String cellData= cell.getstringcell value();

Return celldata;

Catch(Exception e)

Return””;

}
Selenium Interview Questions

26. How to write in the Excel cell, Row num and Col num are the parameters

public static void setCellData(String Result, IntRow, IntColumn) Throws exception


{
Try

Row= ExcelWSheet. getRow (RowNo);


Cell= Row.getCell (CellNo, Row.Return_Blank_AS_Null);
If(Cell = Null)
{
Cell= Row.createCell(CellNO)
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}

27. This is to send the PASS value to the Excel sheet in the result column.

ExcelUtils.setCellData("Pass", 1, 3);

Вам также может понравиться