Selenium Interview Questions

What type of tests have you automated?
Our main focus is to automate test cases to do Regression testing, Smoke testing, and Sanity testing.

How many test cases you have automated per day?                                                         
I did automate 2-5 test scenarios per day when the complexity is limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.

What are the different exceptions you have faced in Selenium WebDriver?
  1. ElementNotVisibleException
  2. StaleElementReferenceException
  3. WebDriverException
  4. IllegalStateException
  5. TimeoutException
  6. NoAlertPresentException
  7. NoSuchWindowException
  8. NoSuchElementException
What is the alternative to driver.get() method to open an URL using Selenium WebDriver?
Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)
driver.get(): open an URL and it will wait till the whole page gets loaded

driver.navigate.to()navigate to an URL and It will not wait till the whole page gets loaded.


How to delete cookies in Selenium?                                                                                    

To delete cookies we use deleteAllCookies() method 

driver.manage().deleteAllCookies();
What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?
driver.getWindowHandle() – It returns a handle of the current page (a unique identifier)

driver.getWindowHandles() – It returns a set of handles of the all the pages available.


How to handle Ajax calls in Selenium WebDriver?
The best approach to handle this kind of situations in selenium is to use dynamic waits (i.e. WebDriverWait in combination with ExpectedCondition)
How to create and run TestNG.xml? 
In TestNG framework, we need to create TestNG XML file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the XML file.
What is Parameterized testing in TestNG?
Parameterized tests allow developers to run the same test over and over again using different values.
Explain what is assertion in Selenium and what are the types of assertion?
Assertion is used as a  verification point. It verifies that the state of the application conforms to what is expected.  The types of assertion are “assert” , “verify” and “waifFor”.
How you can use “submit” a form using Selenium ?
You can use “submit” method on element to submit form-
element.submit () ;
Explain how you can login into any site if it’s showing any authentication popup for password and username?
Pass the username and password with url
 Explain how you can find broken images in a page using Selenium Web driver ?
To find the broken images in a page using Selenium web driver is
  • Get XPath and get all the links in the page using tag name
  • In the page click on each and every link
  • Look for 404/500 in the target page title
Explain using Webdriver how you can perform double click ?
You can perform double click by using
  •  Actions act = new Actions (driver);
  • act.doubleClick(webelement);
 How do you read data from excel ?

FileInputStream fis = new FileInputStream(“path of excel file”);
Workbook wb = WorkbookFactory.create(fis);
Sheet s = wb.getSheet(“sheetName”);
String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue();

Write the code for Reading and Writing to Excel through Selenium ?
FileInputStream fis = new FileInputStream(“path of excel file”);

 Workbook wb = WorkbookFactory.create(fis);

 Sheet s = wb.getSheet("sheetName");

 String value = s.getRow(rowNum).getCell(cellNum).getStringCellValue(); // read data

 s.getRow(rowNum).getCell(cellNum).setCellValue("value to be set"); //write data

 FileOutputStream fos = new FileOutputStream(“path of file”);

 wb.write(fos); //save file


What is the use of getOptions() method ?
getOptions() is used to get the selected option from the dropdown list.

Is WebElement an interface or a class ?
WebDriver is an Interface.

FirefoxDriver is class or an interface and from where is it inherited ?
FirefoxDriver is a class. It implements all the methods of WebDriver interface

What is the use of contextClick() ?
It is used to right click.

How can we capture screenshots in selenium ?
Using getScreenshotAs method of TakesScreenshot interface we can take the screenshots in selenium.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(“D:\\testScreenShot.jpg”));

Where you have applied OOPS in Automation Framework?

ABSTRACTION

In Page Object Model design pattern, we write locators (such as id, name, xpath etc.,) in a Page Class. We utilize these locators in tests but we can’t see these locators in the tests. Literally we hide the locators from the tests.

INHERITANCE

We create a Base Class in the Framework to initialize WebDriver interface, WebDriver waits, Property files, Excels, etc., in the Base Class.
We extend the Base Class in other classes such as Tests and Utility Class. Extending one class into other class is known as Inheritance.

POLYMORPHISM

Combination of overloading and overriding is known as Polymorphism. 
We use implicit wait in Selenium. Implicit wait is an example of overloading. In Implicit wait we use different time stamps such as SECONDS, MINUTES, HOURS etc.,
Declaring a method in child class which is already present in the parent class is called Method Overriding. Examples are get and navigate methods of different drivers in Selenium 

Selenium Basic

What are the benefits of Automation Testing?
Benefits of Automation testing are:
  1. Supports execution of repeated test cases
  2. Aids in testing a large test matrix
  3. Enables parallel execution
  4. Encourages unattended execution
  5. Improves accuracy thereby reducing human-generated errors
  6. Saves time and money
Why should Selenium be selected as a test tool?
Selenium
  1. is a free and open source
  2. have a large user base and helping communities
  3. have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
  4. have great platform compatibility (Windows, Mac OS, Linux etc.)
  5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
  6. has fresh and regular repository developments
  7. supports distributed testing
What is Selenium? What are the different Selenium components?
Selenium is one of the most popular automated testing suites.
The suite package constitutes of the following sets of tools(Selenium Components):


  • Selenium Integrated Development Environment (IDE) – Selenium IDE is a record and playback tool. It is distributed as a Firefox Plugin.
  • Selenium Remote Control (RC) – Selenium RC is a server that allows a user to create test scripts in the desired programming language. It also allows executing test scripts within the large spectrum of browsers.
  • Selenium WebDriver – WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility to automate.
  • Selenium Grid – Selenium Grid is used to distribute your test execution on multiple platforms and environments concurrently.
What is a hub in Selenium Grid?      
  A hub is a server or a central point that controls the test executions on different machines.
What is a node in Selenium Grid?         
 Node is the machine which is attached to the hub. There can be multiple nodes in Selenium Grid.
What are the Programming Languages supported by Selenium WebDiver?
  • Java
  • C#
  • Python
  • Ruby
  • Perl
  • PHP
What are the testing types that can be supported by Selenium?


  1. Functional Testing
  2. Regression Testing
What are the limitations of Selenium?
Following are the limitations of Selenium:
  • Selenium supports testing of only web-based application.
  • Captcha and Barcode readers cannot be tested using Selenium
  • Reports can only be generated using third-party tools like TestNG or JUnit.
  • The user is expected to possess prior programming language knowledge.
What is Selenese?
Selenese is the language which is used to write test scripts in Selenium IDE.
What are the different types of locators in Selenium?
The locator can be termed as an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely we have different types of locators in Selenium:
  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector
  • DOM

What is the difference between assert and verify commands?
Assert: Assert command checks whether the given condition is true or false. Let’s say we assert whether the given element is present on the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the execution would stop and no further test would be executed.
Verify: Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the program execution doesn’t halt i.e. any failure during verification would not stop the execution and all the test steps would be executed.
What is an XPath?
XPath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data.
What is the difference between “/” and “//” in Xpath?
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.
                         /html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input
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.
                                             //input[@id='email']
What do we mean by Selenium 1 and Selenium 2?
Selenium RC and WebDriver, in a combination, are popularly known as Selenium 2. Selenium RC alone is also referred as Selenium 1.
How do I launch the browser using WebDriver?


The following syntax can be used to launch Browser:

WebDriver driver = new FirefoxDriver();
WebDriver driver = new ChromeDriver();
WebDriver driver = new InternetExplorerDriver();
Here, WebDriver is an interface, driver is a reference variable, FirefoxDriver() is a Constructornew is a keyword, and new FirefoxDriver() is an Object.

Is the FirefoxDriver a Class or an Interface?          
 FirefoxDriver is a Java class, and it implements the WebDriver interface.
What are the different types of Drivers available in WebDriver?
The different drivers available in WebDriver are:
  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver
What are the different types of waits available in WebDriver?
There are two types of waits available in WebDriver:
  1. Implicit Wait
  2. Explicit Wait
  3. Fluent Wait
Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.


                  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit waits are applied for a particular instance only.


                      WebDriverWait wait = new WebDriverWait(driver,30);

wait.until(ExpectedConditions.elementToBeClickable(By.xpath(“//div[contains(text(),’COMPOSE’)]”)));
 
 Fluent Wait : Fluent Wait looks for a web element repeatedly at regular intervals until timeout happens or until the object is found.

Fluent Wait commands are most useful when interacting with web elements that can take longer durations to load. This is something that often occurs in Ajax applications.

//Declare and initialise a fluent wait
FluentWait wait = new FluentWait(driver);
//Specify the timout of the wait
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
//Sepcify polling time
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
//Specify what exceptions to ignore
wait.ignoring(NoSuchElementException.class)

 
How to type in a textbox using Selenium?
The user can use sendKeys(“String to be entered”) to enter the string in the textbox.
Syntax:

WebElement username = driver.findElement(By.id(“Email”));
username.sendKeys(“sth”);
How to clear the text in the text box using Selenium WebDriver?                                                       
By using clear() method                                                                                                          
How can you find if an element in displayed on the screen?
  1. isDisplayed()
  2. isSelected()
  3. isEnabled()
Syntax:
isDisplayed():
boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();
isSelected():
boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isSelected();
isEnabled():
boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();
How can we get a text of a web element?

Get command is used to retrieve the inner text of the specified web element.

Syntax:
String Text = driver.findElement(By.id(“Text”)).getText();

How to get an attribute value using Selenium WebDriver?                                                                 
By using getAttribute(value);
How to fetch the current page URL in Selenium?                                                                               
To fetch the current page URL, we use getCurrentURL()
How to select value in a dropdown?
The value in the dropdown can be selected using WebDriver’s Select class.
Syntax:
selectByValue:

Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
selectByValue.selectByValue(“greenvalue”);
selectByVisibleText:

Select selectByVisibleText = new Select (driver.findElement(By.id(“SelectID_Two”)));
selectByVisibleText.selectByVisibleText(“Lime”);

selectByIndex:

Select selectByIndex = new Select(driver.findElement(By.id(“SelectID_Three”)));
selectByIndex.selectByIndex(2);


What are the different types of navigation commands?


Following are the navigation commands:

navigate().back() – The above command requires no parameters and takes back the user to the previous webpage in the web browser’s history.
Sample code:
driver.navigate().back();
navigate().forward() – This command lets the user to navigate to the next web page with reference to the browser’s history.
Sample code:
driver.navigate().forward();
navigate().refresh() – This command lets the user to refresh the current web page there by reloading all the web elements.
Sample code:
driver.navigate().refresh();
navigate().to() – This command lets the user to launch a new web browser window and navigate to the specified URL.
Sample code:
driver.navigate().to(“https://google.com”);

How to handle frame in WebDriver?
An inline frame acronym as iframe is used to insert another document within the current HTML document or simply a web page into a web page by enabling nesting.
Select by id
driver.switchTo().frame(ID of the frame);
using tagName
driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));
using index
driver.switchTo().frame(0);
using Name of Frame
driver.switchTo().frame(“name of the frame”);
Select Parent Window
driver.switchTo().defaultContent();

When do we use findElement() and findElements()?
findElement(): findElement() is used to find the first element in the current web page matching to the specified locator value. Take a note that only first matching element would be fetched.
Syntax: WebElement element = driver.findElement(By.xpath(“//div[@id=’example’]//ul//li”));
findElements(): findElements() is used to find all the elements in the current web page matching to the specified locator value. Take a note that all the matching elements would be fetched and stored in the list of WebElements.
Syntax:
List <WebElement> elementList = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));

What is the difference between driver.close() and driver.quit command?
close():close() method closes the web browser window that the user is currently working on.
quit(): quit() method closes down all the windows that the program has opened. 
How can we handle web-based pop up?
WebDriver offers the users with a very efficient way to handle these pop-ups using Alert interface. 
  • void dismiss() – The accept() method clicks on the “Cancel” button as soon as the pop-up window appears.
  • void accept() – The accept() method clicks on the “Ok” button as soon as the pop-up window appears.
  • String getText() – The getText() method returns the text displayed on the alert box.
  • void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
Syntax:

                Alert alert = driver.switchTo().alert();
               alert.accept(); or alert.dismiss();

Can Selenium handle windows based pop up?
Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up cannot be handled using Selenium. But There are several third-party tools available for handling window based pop-ups along with the selenium like AutoIT, Robot class etc.
How to assert title of the web page?
//verify the title of the web page
assertTrue(“The title of the window is incorrect.”,driver.getTitle().equals(“Title of the page”));


How to mouse hover on a web element using WebDriver?

Used Action Interface to mouse hover on a drop down which then opens a list of options.

// Instantiating Action Interface

Actions actions=new Actions(driver);
// hovering on the dropdown
actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform();
// Clicking on one of the items in the list options
WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
subLinkOption.click();


How to capture screenshot in WebDriver?

// Code to capture the screenshot

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Code to copy the screenshot in the desired location

FileUtils.copyFile(scrFile, new File("C:\\CaptureScreenshot\\google.jpg"))

What are Junit annotations?
Following are the JUnit Annotations:
  • @Test: Annotation lets the system know that the method annotated as @Test is a test method. There can be multiple test methods in a single test script.
  • @Before: Method annotated as @Before lets the system know that this method shall be executed every time before each of the test methods.
  • @After: Method annotated as @After lets the system know that this method shall be executed every time after each of the test method.
  • @BeforeClass: Method annotated as @BeforeClass lets the system know that this method shall be executed once before any of the test methods.
  • @AfterClass: Method annotated as @AfterClass lets the system know that this method shall be executed once after any of the test methods.
  • @Ignore: Method annotated as @Ignore lets the system know that this method shall not be executed.
What are the different types of frameworks?
  1. Data Driven Testing Framework: Data Driven Testing Framework helps the user segregate the test script logic and the test data from each other. It lets the user store the test data into an external database. The data is conventionally stored in “Key-Value” pairs. Thus, the key can be used to access and populate the data within the test scripts.
  2. Keyword Driven Testing Framework: The Keyword Driven testing framework is an extension to Data-driven Testing Framework in a sense that it not only segregates the test data from the scripts, it also keeps the certain set of code belonging to the test script into an external data file.
  3. Hybrid Testing Framework: Hybrid Testing Framework is a combination of more than one above mentioned frameworks. The best thing about such a setup is that it leverages the benefits of all kinds of associated frameworks.
  4. Behavior Driven Development Framework: Behavior Driven Development framework allows automation of functional validations in easily readable and understandable format to Business Analysts, Developers, Testers, etc.
What is Object Repository? How can we create Object Repository in Selenium?
Object Repository is used to store locators in a centralized location instead of hard-coding them within the scripts.We do create a property file (.properties) to store all the element locators and these property files act as an object repository in Selenium WebDriver.
What is Page Object Model in Selenium?
In the Page Object Model Design Pattern, each web page is represented as a class. All the objects related to a particular page of a web application are stored in a class.
What are the annotations available in TestNG?
@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test