Skip to main content

Selenium with Java Interview Questions and Answers

What exception will be thrown when we use "findElement" method?

NoSuchElementException
will be thrown when the locator is not found in the DOM and no longer available.

How will you handle popups windows in Selenium?

We can handle popups in Selenium is simple. It provides various methods from WebDriver interface. They are,

1. getWindowHandle()
2. getWindowHandles()

getWindowHandle() - deals with current window
getWindowHandles() - it manages with multiple windows and returns set of instances

Let me show an example to understand this better,

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;

public class PopupDemo { 

private WebDriver driver; 

@BeforeTest 
public void setUp() 
{
System.setProperty("webdriver.firefox.bin", "C:\\Users\\smshri\\AppData\\Local\\Mozilla Firefox\\firefox.exe"); driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("http://www.hdfcbank.com"); 

@Test 
public void openPopup() 
{
driver.findElement(By.id("loginsubmit")).click(); 
String currentWindowId = driver.getWindowHandle(); System.out.println(currentWindowId); 
countAllWindows(driver); 

public void countAllWindows(WebDriver driver) 
Set windows = driver.getWindowHandles();
Iterator iterator = windows.iterator();

int countWindow = 0; 

while(iterator.hasNext()) 
countWindow++; 
System.out.println(iterator.next().toString());
System.out.println("Total active windows :" + countWindow);
}
}

The output would be for the above script.,
{d079b8e9-d921-4ddf-84b8-b06c4aa79580}
{d079b8e9-d921-4ddf-84b8-b06c4aa79580}
{92825fbd-bfcf-4d44-990d-ad2e2708eae1}


Total active windows :2

How will you handle calendar control in Selenium?

To handle calendar component in selenium is quite simple. To achieve this, I have used jQuery Datepicker component. You can get that source from here.

And write the following selenium script and execute the same.

import java.util.List;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class DatePickerDemo {

private WebDriver driver;

@BeforeTest
public void setUp()
{
System.setProperty("webdriver.firefox.bin", "C:\\Local\\Mozilla Firefox\\firefox.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("file:///Z:/Selenium/Testing/src/DatePickerDemo.html");
}

@Test
public void pickDate()
{
driver.findElement(By.id("datepicker")).click();
List dates = driver.findElements(By.xpath("//table[@class='ui-datepicker-calendar']//td"));
for (WebElement element : dates)
{
System.out.println("Picked Date:" + element.getText());
String date = element.getText();
if (date.equalsIgnoreCase("18"))
{
element.click();
break;
}}}}


What is the method name to clear text box control in Selenium?

In order to clear text box, there are two ways in selenium. One is, CLEAR() method.
Lets look into this script.

driver.findElement(By.id("textfield")).clear();

otherwise, we can pass empty string to SendKeys() method.
Example: driver.findElement(By.id("textfield")).sendKeys("");

How will you pass text without using "sendKeys" method in Selenium?
Yes. We can pass value to the textbox without using SendKeys() method. Look at the below script.

JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("document.getElementById('txtuser').value='textuser@gmail.com'");


When to use ImplicitWait and ExplicitWait commands?

ExplicitWait will wait until the specified condition meets true for a particular component. This can be achieved by WebDriverWait command.

WebDriver driver = new FirefoxDriver();
driver.get("http://www.stackoverflow.com");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));


ImplicitWait will wait for given time period for each element if the page contains many elements.

Example: driver.manage().timeouts().implicitlywait(10, TimeUnit.SECONDS);

Are WebElement and WebDriver Interface or a class type?

Yes. Both are Interface

Difference between "Absolute Path" and "Relative Path" in Selenium?


Absolute Path: - Refers to the complete path of the element is present i.e from root tag to actual element located tag.

Relative Path: - Deals with current tag where the element is present

relative path will be = //*[@id="txtuser"]


What are the Synchronization methods available in Selenium?

The Synchronization commands are classified into two types. They are,

1. Conditional Synchronization
2. Unconditional Synchronization

Conditional Synchronization: it works based on the condition meets the expectation so that Selenium WebDriver will wait until the given time period if the specified condition gets satisfied.

The implicit wait and explicit wait statements are falling under this category.

Unconditional Synchronization: It forces to make the Selenium WebDriver has to wait for certain amount of time.

Wait() and Sleep() statements are belongs to this category. The main limitation of these statements are, it should wait till the given time period even after the elements have loaded earlier.

How do you handle "Dynamic IDs" in selenium?

What is the major difference between "Verify" and "Assert" commands in selenium?

Both commands are used to check whether an element is present or not in the webpage.
However, there are some unique differences between these two. Let us see what are they.

Assert - when assertion is failed during the execution, the remaining test scripts will not be executed. Generally, it returns true if the condition meets the requirement. Else, the code should be skipped.

Verify - it performs opposite manner of Assert statement. it continues to execute the scripts even the particular line of code got failed and final test case result would be logged as FAILED.

What are the locators available in Selenium?
  • ID 
  • Name 
  • Class 
  • CssClass 
  • TagName 
  • LinkText 
  • PartialLinkText 
  • Xpath 
Can you tell me the logic to read the data from excel column without Null?

For example, there are 3 columns in Excel sheet like A,B,C. A and C columns have data and "B" has no data. To achieve this scenario, look at this following script. I have already created an excel file with three columns with one empty column. This script returns the number of cells have Null.

import jxl.Workbook;
import jxl.Sheet;
import java.io.File;
import java.io.FileInputStream;

public class ExcelNullValidation {

Workbook book;
Sheet sheet;

String fileLoc = "E:\\Selenium\\Samples\\src\\testData.xls";
public void ReadExcel() throws Exception
{
File file = new File(fileLoc);
FileInputStream fis = new FileInputStream(file);

book = Workbook.getWorkbook(fis);
sheet = book.getSheet(0);
int cnt=0;

int tRows = sheet.getRows();
int tCols = sheet.getColumns();

for(int row=0; row{
for (int col=0; col{

if (sheet.getCell(col,row).getContents().isEmpty())
cnt++;
}
}
System.out.println(cnt);
}

public static void main(String[] args) throws Exception {
ExcelNullValidation obj = new ExcelNullValidation();
obj.ReadExcel();
}
}


How will you handle tabs in Selenium Webdriver using Java? Or When to use "CssClass" locator in Selenium?

We can open a new tab or navigate to some other tabs which are currently opened in Selenium Webdriver with the help of Java programming language. Let's have a look at this code fragmentation.

driver.findElement(By.CssSelector("body")).sendKeys(Keys.CONTROL + "t");
The above script will navigate to next tab. Similarly, we can close the tabs that currently opened in a browser.
driver.findElement(By.CssSelector("body")).sendKeys(Keys.CONTROL + "w");

This is how we can handle tabs in a web browser.



Comments

Popular posts from this blog

Query to find Nth Maximum and Minimum value from the Table

Hi, This query will fetch the rows which is the most large value / maximum value. --Maximum value SELECT MAX( spend )   FROM edw_aggregate.vw_agg_order_automation  WHERE spend < ( SELECT MAX( spend )                  FROM edw_aggregate.vw_agg_order_automation ); The above query will only fetch top most value from the table. If we want to fetch Nth  maximum / minimum value, look into this query.   --Nth Minimum/Max SELECT MIN( spend )   FROM edw_aggregate.vw_agg_order_automation   where spend in (SELECT top 5 spend FROM edw_aggregate.vw_agg_order_automation order by spend desc) Thanks

How to Handle Plain Javascript alert dialog buttons using Selenium with Java?

I have HTML page like this, < input type = "button" id = "btnlogin" value = "Login" onclick = "goToRegister()" > And the javascript is, < script language = "javscript" type = "text/javascript" > function goToRegister () { alert ( "Login Successful!" ); window . location . href = "Register.html" ; } </ script > In the selenium script , @Test public void goToRegisterPage () { System . out . println ( "goToRegisterPage" ); WebDriverWait wait = new WebDriverWait ( driver , 10 ); Alert alert = wait . until ( ExpectedConditions . alertIsPresent ()); alert . accept (); driver . get ( "file:///X://selenium//Register.html" ); } @BeforeMethod public void beforeMethod () { System . out . println ( "beforeMeth