Other Useful Links:
- Manual Testing Interview Questions (01-40)
- Manual Testing Interview Questions (41-80)
- Java Interview Questions for QA (01-50)
- Java Interview Questions for QA (51-100)
- Java Programs for QA Automation Interview (01-15)
- Java Programs for QA Automation Interview (16-30)
- TestNG Interview Questions for QA (01-20)
- TestNG Interview Questions for QA (21-40)
- Maven Interview Questions for QA Automation Interview (01-15)
- Maven Interview Questions for QA Automation Interview (16-30)
- Most Frequently Asked API Testing Interview Questions (01-20)
- Most Frequently Asked API Testing Interview Questions (21-40)
36. What is JavaScriptExecutor?
JavaScriptExecutor is a Selenium Webdriver interface that allows you to run JavaScript.
To run javascript on the selected window or current page, JavaScriptExecutor provides two methods: "executescript" and "executeAsyncScript."
To show alert using JavaScriptExecutor
js.executeScript("alert('Welcome');");
Perform click operation on button using JavaScriptExecutor
js.executeScript("arguments[0].click();", button);
Fetch URL of site
String url = js.executeScript("return document.URL;").toString();
Fetching the Domain Name of the site.
String DomainName = js.executeScript("return document.domain;").toString();
Launch new URL
js.executeScript("window.location = 'http://demo.Test.com/'");
Vertical scroll down by 800 pixels
js.executeScript("window.scrollBy(0,800)");
Scroll page till end
js.executeScript("window.scrollTo(0,document.body.scrollHeight)");
Scroll till particular element
js.executeScript("arguments[0].scrollIntoView();",element);
JavaScriptExecutor is a Selenium Webdriver interface that allows you to run JavaScript.
To run javascript on the selected window or current page, JavaScriptExecutor provides two methods: "executescript" and "executeAsyncScript."
37. JavaScriptExecutor is class or Interface?
Interface
Interface
38. What is Sikuli?
Sikuli is a GUI-based open-source test automation tool.
It's mostly used for dealing with web page elements and handling popup windows.
Sikuli interacts with parts of web sites and windows popups using "Image Recognition" and "Control GUI" techniques.
In Sikuli, all site elements are stored as photos and kept within the project.
Sikuli is a GUI-based open-source test automation tool.
It's mostly used for dealing with web page elements and handling popup windows.
Sikuli interacts with parts of web sites and windows popups using "Image Recognition" and "Control GUI" techniques.
In Sikuli, all site elements are stored as photos and kept within the project.
39. Name few exception in Selenium
InterruptedException
ElementNotVisibleException
NoSuchElementException
NoSuchAttributeException
NoSuchFrameException
NoSuchWindowException
NoAlertPresentException
TimeOutException
InterruptedException
ElementNotVisibleException
NoSuchElementException
NoSuchAttributeException
NoSuchFrameException
NoSuchWindowException
NoAlertPresentException
TimeOutException
40. Desired Capabilities
Selenium's Desired Capabilities class is used to configure browser attributes for cross-browser testing of web applications.
It saves capabilities as key-value pairs, which are used to set browser attributes such as browser name, browser version, system path of browser driver, and so on, in order to decide browser behaviour at run time.
We can configure driver instances like FirefoxDriver, ChromeDriver, InternetExplorerDriver by using desired capabilities.
getBrowserName()
setBrowserName()
getVersion()
setVersion()
getPlatform()
setPlatform()
getCapability()
setCapability()
Example:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
Selenium's Desired Capabilities class is used to configure browser attributes for cross-browser testing of web applications.
It saves capabilities as key-value pairs, which are used to set browser attributes such as browser name, browser version, system path of browser driver, and so on, in order to decide browser behaviour at run time.
We can configure driver instances like FirefoxDriver, ChromeDriver, InternetExplorerDriver by using desired capabilities.
getBrowserName()
setBrowserName()
getVersion()
setVersion()
getPlatform()
setPlatform()
getCapability()
setCapability()
41. How to Take Screenshot in Selenium WebDriver
For bug investigation, a screenshot taken using Selenium Webdriver is used. During the execution, the Selenium webdriver can snap screenshots automatically.
However, if users need to take a screenshot on their own, they must utilise the TakeScreenshot method, which instructs the WebDrive to take a screenshot and save it in Selenium.
Example:
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;
public class Test{
public static void main(String[] args){
WebDriver driver;
System.setProperty("WebDriver.gecko.driver","PathToGeckoDriver");
driver = new FirefoxDriver();
driver.get("http://www.Test.com");
File src = ((TakeScreenshot)driver).getScreenShotAs(OutputType.FILE);
try{
FileUtils.copyFile(src,new File("NewFilePath"));
}catch(Exception e){
System.out.println(e.getMessage());
}
driver.close();
}
}
For bug investigation, a screenshot taken using Selenium Webdriver is used. During the execution, the Selenium webdriver can snap screenshots automatically.
However, if users need to take a screenshot on their own, they must utilise the TakeScreenshot method, which instructs the WebDrive to take a screenshot and save it in Selenium.
42. TakeScreenShot is class or Interface?
Interface
Interface
43. Launch a browser using selenium
public class LaunchBrowser{
public static void main(String[] args){
WebDriver driver;
System.setProperty("WebDriver.gecko.driver",PathToGeckoDriver);
driver = new FireFoxDriver();
driver.get("http://www.google.com");
driver.quit();
}
}
WebDriver is an interface.
driver is a reference variable.
FireFoxDriver is a class.
44. Explain driver.manage().window().maximize();
driver is reference variable
There is a method named 'manage' and is declared inside the WebDriver interface. This method's return type is Options.
The Options interface is a subinterface of the WebDriver interface and has sub method Window.
A method called maximise() in the Window interface returns void.
driver is reference variable
There is a method named 'manage' and is declared inside the WebDriver interface. This method's return type is Options.
The Options interface is a subinterface of the WebDriver interface and has sub method Window.
A method called maximise() in the Window interface returns void.
45. Waits in Selenium
Ajax and Javascript are used to create the majority of web apps. The items we want to interact with may load at different times when a page is loaded by the browser.
Not only does it make it difficult to identify the element but also if the element is not located it will throw an “ElementNotVisibleException” exception. We can solve this issue with Selenium Waits.
Consider the following case in which we must utilise both implicit and explicit waits in our test. Assume that the implicit wait time is 20 seconds and the explicit wait time is 10.
If the element is not located within the time frame set by the explicit wait (10 seconds), it will use the implicit wait time frame before generating a "ElementNotVisibleException" (20 seconds).
Ajax and Javascript are used to create the majority of web apps. The items we want to interact with may load at different times when a page is loaded by the browser.
Not only does it make it difficult to identify the element but also if the element is not located it will throw an “ElementNotVisibleException” exception. We can solve this issue with Selenium Waits.
Consider the following case in which we must utilise both implicit and explicit waits in our test. Assume that the implicit wait time is 20 seconds and the explicit wait time is 10.
If the element is not located within the time frame set by the explicit wait (10 seconds), it will use the implicit wait time frame before generating a "ElementNotVisibleException" (20 seconds).
46. Implicit Wait in Selenium
The Implicit Wait command in Selenium instructs the web driver to wait for a set amount of time before throwing a "No Such Element Exception."
The default value is zero. The web driver will wait for the element for that amount of time we set before throwing an exception.
Syntax: driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
Example:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Test {
private WebDriver driver;
private String baseurl;
Private WebElement element;
@BeforeMethod
public void setup() throws Exception{
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
baseurl = "http://www.google.com";
}
@Test
public void LaunchBrowser(){
driver.get(baseurl);
driver.manage().window().maximize();
}
@AfterMethod
public void TearDown() throws Exception{
driver.quit();
}
}
The Implicit Wait command in Selenium instructs the web driver to wait for a set amount of time before throwing a "No Such Element Exception."
The default value is zero. The web driver will wait for the element for that amount of time we set before throwing an exception.
Syntax: driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);
47. Explicit Wait in Selenium
In Selenium, the Explicit Wait command tells the Web Driver to wait for specific conditions (Expected Conditions) or a set amount of time to pass before throwing a "ElementNotVisibleException" exception.
It's an intelligent type of wait, but it can only be used on certain items.
Because it waits for dynamically loaded Ajax components, it provides greater alternatives than implicit wait.
The Expected Conditions that can be utilised with Selenium Explicit Wait are listed below.
alertIsPresent()
elementSelectionStateToBe()
elementToBeClickable()
elementToBeSelected()
frameToBeAvaliableAndSwitchToIt()
invisibilityOfTheElementLocated()
invisibilityOfElementWithText()
presenceOfAllElementsLocatedBy()
presenceOfElementLocated()
textToBePresentInElement()
textToBePresentInElementLocated()
textToBePresentInElementValue()
titleIs()
titleContains()
visibilityOf()
visibilityOfAllElements()
visibilityOfAllElementsLocatedBy()
visibilityOfElementLocated()
Example:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Test {
WebDriver driver;
@BeforeMethod
public void setup() throws Exception{
driver = new ChromeDriver();
driver.get("http://www.gmail.com/login");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS) ;
}
@Test
public void Login(){
WebElement email = driver.findElement(By.Id("Email"));
WebElement pass = driver.findElement(By.Id("Password"));
WebElement login_btn = driver.findElement(By.Id("Login_Button"));
email.sendKeys("abcd@gmail.com");
pass.sendKeys("test@1234");
login_btn.click();
WebDriverWait wait=new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id=TestId]")));
driver.findElement(By.xpath("//div[@id=TestId]").click();
}
@AfterMethod
public void TearDown() throws Exception{
driver.quit();
}
}
In Selenium, the Explicit Wait command tells the Web Driver to wait for specific conditions (Expected Conditions) or a set amount of time to pass before throwing a "ElementNotVisibleException" exception.
It's an intelligent type of wait, but it can only be used on certain items.
Because it waits for dynamically loaded Ajax components, it provides greater alternatives than implicit wait.
alertIsPresent()
elementSelectionStateToBe()
elementToBeClickable()
elementToBeSelected()
frameToBeAvaliableAndSwitchToIt()
invisibilityOfTheElementLocated()
invisibilityOfElementWithText()
presenceOfAllElementsLocatedBy()
presenceOfElementLocated()
textToBePresentInElement()
textToBePresentInElementLocated()
textToBePresentInElementValue()
titleIs()
titleContains()
visibilityOf()
visibilityOfAllElements()
visibilityOfAllElementsLocatedBy()
visibilityOfElementLocated()
48. Fluent Wait in Selenium
In Selenium, the Fluent Wait is used to specify the maximum amount of time the web driver should wait for a condition, as well as the frequency with which we want to check the condition before throwing a "ElementNotVisibleException" exception.
It keeps looking for the web element at regular intervals until it finds it or timeouts.
Example:
Wait wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(5, SECONDS).ignoring(NoSuchElementException.class);
In Selenium, the Fluent Wait is used to specify the maximum amount of time the web driver should wait for a condition, as well as the frequency with which we want to check the condition before throwing a "ElementNotVisibleException" exception.
It keeps looking for the web element at regular intervals until it finds it or timeouts.
49. Implicit Wait vs Explicit Wait
50. Action Class in Selenium
Action Class in Selenium is a built-in feature provided by selenium for handling keyboard and mouse events.
The Advanced User Interactions API is used to handle specific keyboard and mouse events. It contains the Actions and Action classes required to carry out these occurrences.
clickAndHold(): Clicks at the current mouse position (without releasing it).
contextClick(): Performs Right Click Mouse Action
doubleClick(): Double-clicks where the mouse is currently positioned.
dragAndDrop(source, target): Performs a click-and-hold at the source element's location, then moves to the target element's location and releases the mouse.
keyDown(modifier_key): Performs a modifier key press. If the modifier key is not released, future interactions may presume it is still pressed.
moveByOffset(x-offset, y-offset): Moves the mouse by the supplied offset from its present position (or 0,0).
moveToElement(toElement): Moves the mouse to that element.
release(): Releases the depressed left mouse button at the current mouse location
sendKeys(onElement, charsequence): The element receives a string of keystrokes.
Below is the whole WebDriver code to check the background color of the <TR> element before and after the mouse-over:
Example:
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class Test{
public static void main(String[] args) {
String baseUrl = "http://demo.Testing.com/test/newtours/";
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement link_Home = driver.findElement(By.linkText("Home"));
WebElement td_Home =driver.findElement(By.xpath("//div[@class="td_home_div"]"));
Actions builder = new Actions(driver);
Action mouseOverHome = builder.moveToElement(link_Home).build();
String bgColor = td_Home.getCssValue("background-color");
System.out.println("Before hover: " + bgColor);
mouseOverHome.perform();
bgColor = td_Home.getCssValue("background-color");
System.out.println("After hover: " + bgColor);
driver.close();
}
}
Action Class in Selenium is a built-in feature provided by selenium for handling keyboard and mouse events.
The Advanced User Interactions API is used to handle specific keyboard and mouse events. It contains the Actions and Action classes required to carry out these occurrences.
clickAndHold(): Clicks at the current mouse position (without releasing it).
contextClick(): Performs Right Click Mouse Action
doubleClick(): Double-clicks where the mouse is currently positioned.
dragAndDrop(source, target): Performs a click-and-hold at the source element's location, then moves to the target element's location and releases the mouse.
keyDown(modifier_key): Performs a modifier key press. If the modifier key is not released, future interactions may presume it is still pressed.
moveByOffset(x-offset, y-offset): Moves the mouse by the supplied offset from its present position (or 0,0).
moveToElement(toElement): Moves the mouse to that element.
release(): Releases the depressed left mouse button at the current mouse location
sendKeys(onElement, charsequence): The element receives a string of keystrokes.
51. Type "HELLO" using Action and Actions class
Actions builder = new Actions(driver);
Action seriesOfActions = builder.moveToElement(element)
.click()
.keyDown(element,Keys.SHIFT)
.sendKeys(element,"hello")
.keyUp(element,Keys.SHIFT)
.doubleClick(element)
.contextClick()
.build();
seriesOfActions.perform();
52. How to Drag and Drop in Selenium WebDriver
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;
import org.testng.annotations.Test;
public class DragAndDrop {
WebDriver driver;
@Test
public void DragnDrop()
{
System.setProperty("webdriver.chrome.driver","PATH");
driver= new ChromeDriver();
driver.get("http://demo.tesi=ting.com/test/drag_drop.html");
// Element which needs to drag
WebElement From=driver.findElement(By.xpath("XPATH1"));
// Target
WebElement To=driver.findElement(By.xpath("XPATH2"));
// Drag and drop with the Action class
Actions act=new Actions(driver);
// Dragged and dropped
act.dragAndDrop(From, To).build().perform();
}
}
53. How to Upload a File using Selenium Webdriver
Uploading files in WebDriver is as simple as entering the path of the file to be uploaded into the sendKeys() method on the file-select input box.
Example:
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Test {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
String baseUrl = "http://demo.testing.com/test/upload/";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement uploadElement = driver.findElement(By.id("uploadfile_btn"));
// in the file-selection input area, type the file path
uploadElement.sendKeys("C:\\newhtml.html");
// click the "UploadFile" button
driver.findElement(By.name("send")).click();
}
}
54. How to Use Selenium Webdriver to Find All/Broken Links
import java.io.IOException;
import java.net.*;
import java.util.*;
import org.openqa.selenium.*;
public class BrokenLinks {
private static WebDriver driver = null;
public static void main(String[] args) {
String homePage = "http://www.test.com";
String url = "";
HttpURLConnection huc = null;
int respCode = 200;
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(homePage);
List<WebElement> links = driver.findElements(By.tagName("a"));
Iterator<WebElement> it = links.iterator();
while(it.hasNext()){
url = it.next().getAttribute("href");
if(url == null || url.isEmpty()){
System.out.println("The URL is empty or not set up.");
continue;
}
if(!url.startsWith(homePage)){
System.out.println("This URL should be avoided since it belongs to a different domain.");
continue;
}
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode >= 400){
System.out.println(url+" is a broken link");
}
else{
System.out.println(url+" is a valid link");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
driver.quit();
}
}
55. Page Object Model
Page Object Model also known as POM is a design pattern in selenium that creates an Object Repository for web UI elements.
It is useful in reducing code duplication and improves test maintenance.
In POM, for each web page in the application, there should be a corresponding Page Class. This Page class will identify the WebElements on the web page and includes Page methods that operate on them.
Advantages of POM:
User interface activities and flows should be separated from verification, according to the Page Object Design Pattern. This concept makes our code more readable and understandable.
The second advantage is that the object repository is independent of test cases, allowing us to reuse the same object repository with different tools. For example, we can combine Page Object Model with TestNG/JUnit for functional testing and JBehave/Cucumber for acceptability testing using Selenium.
Because of the reusable page methods in the POM classes, code gets less and more optimised.
Methods are given more realistic names that are easier to associate with the user interface function. The function name will be 'gotoHomePage()' if we land on the home page after pressing the button.
Page Object Model also known as POM is a design pattern in selenium that creates an Object Repository for web UI elements.
It is useful in reducing code duplication and improves test maintenance.
In POM, for each web page in the application, there should be a corresponding Page Class. This Page class will identify the WebElements on the web page and includes Page methods that operate on them.
User interface activities and flows should be separated from verification, according to the Page Object Design Pattern. This concept makes our code more readable and understandable.
The second advantage is that the object repository is independent of test cases, allowing us to reuse the same object repository with different tools. For example, we can combine Page Object Model with TestNG/JUnit for functional testing and JBehave/Cucumber for acceptability testing using Selenium.
Because of the reusable page methods in the POM classes, code gets less and more optimised.
Methods are given more realistic names that are easier to associate with the user interface function. The function name will be 'gotoHomePage()' if we land on the home page after pressing the button.
56. Page Factory
Page Factory is a Selenium WebDriver inherent Page Object Model framework concept that is highly efficient.
In addition, we use annotations @FindBy to find WebElement using Selenium's PageFactory class.
As attributes, @FindBy accepts tagName, partialLinkText, name, linkText, id, css, className, and xpath.
Syntax: @FindBy(id="elementId") WebElement element;
Page Factory - page object design pattern uses AjaxElementLocatorFactory to identify WebElements only when they are utilised in any operation.
initElements is a static method used in PageFactory class. Using initElements method one can initialize all the elements located by @FindBy annotations.
Page Factory is a Selenium WebDriver inherent Page Object Model framework concept that is highly efficient.
In addition, we use annotations @FindBy to find WebElement using Selenium's PageFactory class.
As attributes, @FindBy accepts tagName, partialLinkText, name, linkText, id, css, className, and xpath.
Syntax: @FindBy(id="elementId") WebElement element;
Page Factory - page object design pattern uses AjaxElementLocatorFactory to identify WebElements only when they are utilised in any operation.
initElements is a static method used in PageFactory class. Using initElements method one can initialize all the elements located by @FindBy annotations.
57. POM vs Page Factory
58. Singleton Design Pattern:
The Singleton design pattern is used when we create a class that can only have one instance at any one time.
It comes in handy when you need to use the same class object across multiple classes or frameworks.
If a singleton class is instantiated repeatedly, it must return the same instance.
The steps to build a singleton class are as follows:
Declare constructor of class as private.
Declare a static reference variable of class. To make it available globally, static is required.
Declare a static method with a return type of class object that checks if the class has already been instantiated.
Example:
class SingletonTest{
private static SingletonTestinstance=null;
private SingletonTest(){
System.out.println("Object Created");
}
public static SingletonTest getInstanceOfClass(){
if(instance == null){
instance = new SingletonTest();
}
return instance;
}
}
class TestDemo{
public static void main(String[] args){
SingletonTest first = SingletonTest.getInstanceOfClass();
SingletonTestsecond = SingletonTest.getInstanceOfClass();
}
}
When you run the preceding programme, you will only see print "Object created." once, despite the fact that the class was instantiated twice. The singleton pattern accounts for this. If a class object has been created before, it will not be created again.
The Singleton design pattern is used when we create a class that can only have one instance at any one time.
It comes in handy when you need to use the same class object across multiple classes or frameworks.
If a singleton class is instantiated repeatedly, it must return the same instance.
Declare constructor of class as private.
Declare a static reference variable of class. To make it available globally, static is required.
Declare a static method with a return type of class object that checks if the class has already been instantiated.
59. What is an Object Repository?
A shared storage area for all objects is an object repository.
In the Selenium WebDriver context, objects are the locators used to uniquely identify web elements.
The major advantage of using object repositories is the segregation of objects from test cases. If the locator value of one webelement changes, only the object repository needs to be updated, rather than all test cases where the locator is utilised.
The sorts of object repositories that Selenium WebDriver can construct are as follows.
Object Repository using Properties file
Object Repository using XML file
Data is stored in the properties file in the form of key-value pairs, with the key being unique across the file.
Example:
OR.properties
MobileTesting = //a[text()="Mobile_Testing"]
EmailTextBox = EmailID
SignUpButton = Sign_Up_Button
import java.io.*;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test {
public static void main(String[] args){
WebDriver driver;
System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://demo.testing.com/home/");
driver.manage().window().maximize();
// Load the properties File
Properties pr = new Properties();
FileInputStream fis = new FileInputStream(System.getProperty("user.dir")+"\\OR.properties");
pr.load(fis);
// Nagigate to link Mobile Testing and Back
driver.findElement(By.xpath(pr.getProperty("MobileTesting"))).click();
driver.navigate().back();
// Enter Data into Form
driver.findElement(By.id(pr.getProperty("EmailTextBox"))).sendKeys("abcd@gmail.com");
driver.findElement(By.id(pr.getProperty("SignUpButton"))).click();
}
}
A shared storage area for all objects is an object repository.
In the Selenium WebDriver context, objects are the locators used to uniquely identify web elements.
The major advantage of using object repositories is the segregation of objects from test cases. If the locator value of one webelement changes, only the object repository needs to be updated, rather than all test cases where the locator is utilised.
Object Repository using Properties file
Object Repository using XML file
60. @CacheLookup in PageObjectModel
- @CacheLookup, as the name implies, allows us to decide whether or not to cache a WebElement.
- When this annotation is applied to a WebElement, Selenium is told to store a cache of the WebElement rather than scanning the WebPage for it every time. This allows us to save lot amount of time.
61. When to use and when not to use @Cachelookup annotation
Stale Element and Stale Element Exception
- Even while it's tempting to utilise the @CacheLookup annotation on every element, it's not appropriate for dynamic elements.
- Dynamic elements means the elements which refreshes quite often. For instance, consider a Timer text that changes its value every second.
- A stock price ticker, which changes every few seconds, is another example. These elements are not good candidates for @CacheLookup annotation.
- The explanation behind this is simple: certain items are not suitable candidates for caching because they change often on the web page.
Static elements
- @CacheLookup is great for elements that don't change on the page after it's loaded. These elements make up the majority of the web page's elements.
- As such elements will not change during test execution, the @Cachelookup annotation should be used to optimise test speed.
62. Which OOPs Concepts you used in your current project?
1. Inheritance
We establish a Base Class in a standard Page Object Model to initialise the WebDriver interface, Data Source, Excel Reader, Property File or Config File, WebDriver waits, and so on. We extend the Base Class in our Test Class and Utility Class.We do it by using the extends keyword and achieve the Inheritance.This makes the class more reusable because we don't have to keep writing the same initialization code.
2. Encapsulation
We know that in a POM Project, we construct a distinct class for each page.All of these classes are excellent examples of encapsulation, in which the data of one class is kept separate from that of another. We define the data members using @FindBy and initialise them using a constructor with initElement() to utilize them in the test methods.
3. Polymorphism
Polymorphism is based on the idea of a single interface that supports numerous methods. WebDriver is a browser interface that supports several methods such as ChromeDriver(), IEDriver(), SafariDriver(), and FirefoxDriver() ().
Method Overloading In Selenium
- Methods Overloading is the process of employing two methods with the same name but different parameters in the same class.
- We now use Implicit Wait in Selenium to have the page wait for a set amount of time.
- Because we may supply different Timestamps or TimeUnits like SECONDS, MINUTES, and so on, this is the ideal example of Method Overloading.
Method Overriding In Selenium
- In the WebDriver interface, we use two different methods for navigating or accessing any website i.e. driver.get() and driver.navigate().to().
- Method Overriding is demonstrated by these two methods.
64. How to launch a batch file from Selenium?
- To run Selenium WebDriver automation scripts in Chrome, first download chromedriver.exe and then use the System.setProperty method to set its path as follows:
- System.setProperty("webdriver.chrome.driver", "/absolute/path/to/binary/chromedriver");
- The script produces an error if we fail to declare this path or if we supply the incorrect path.
- When new binaries or browser versions are published, we'll have to check compatibility for each executable again, and if there are any issues, we'll have to repeat the procedure.
- This time-consuming and wasteful method of manually downloading executables, setting their path in scripts, and then executing the scripts is inefficient.
- In current Selenium versions, a "WebDriverManager" class automates this step, allowing us to concentrate on Selenium scripts rather than browser settings.
- It automates the management of WebDriver binaries.
- If the required driver binaries are not already in the local cache, it is downloaded.
- Unless otherwise specified, downloads the most recent version of the browser binary.
- It is no longer necessary to keep driver binaries locally.
- We also won't have to keep track of multiple versions of binary driver files for different browsers.
67. Advance Webdriver Waits
We can make our own Advanced WebDriver Waits or Custom Waits.. A fluent wait looks like this:
- ExpectedConditions class. This is a very useful class that will cover the majority of your requirements. However, there are situations when we require more than what is provided by ExpectedConditions.
- If you look closely at the.until() method, you'll notice that it's an overloaded function that can take two different types of inputs.
- A Function()
- A Predicate()
What is a Function?- Package: com.google.common.base.Function
- A function is a general interface that requires you to implement the methods - apply (F from) - equals (Object obj)
- equals() implementation is optional and will be chosen from the basic implementation.
Example:public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); driver.get("https://testing.com/browser-windows/");
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver); wait.pollingEvery(250, TimeUnit.MILLISECONDS); wait.withTimeout(2, TimeUnit.SECONDS);
Function<WebDriver, Boolean> function = new Function<WebDriver, Boolean>(){ public Boolean apply(WebDriver arg0) { WebElement element = arg0.findElement(By.id("colorVar")); String color = element.getAttribute("color"); System.out.println("The color of the button is " + color); if(color.equals("red")){ return true; } return false; } };
wait.until(function); }
- A Function()
- A Predicate()
- Package: com.google.common.base.Function
- A function is a general interface that requires you to implement the methods - apply (F from) - equals (Object obj)
- equals() implementation is optional and will be chosen from the basic implementation.
68. What criteria do you use to determine which test cases to automate?
- Priority: Some features of the application have a higher chance of failing than others. Such features must be automated as the chance of bug detection is comparatively less using manual testing.
- Repetition: Repeating the test case is not time consuming activity when it comes to automation testing.
- Number of test cases: If the test suite contains more test cases that need to be executed more than once then automating it is a good choice.
- Need of Parallel Testing: Simultaneous execution of test cases on multiple browsers requires more team members, to save such bandwidth test cases are often automated.
- Cross browser /cross platform.
- Experty of team.
- If manual intervention is required to execute a scenario then it would not make much sense to automate it.
- Volume of data input: If the volume of test data is very large then you should automate it.
Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.
Contact:
Email: piyushagrawal.automation@gmail.com
Follow on LinkedIn: Piyush Agrawal - LinkedIn
Follow on YouTube: Piyush Agrawal - Youtube
Greetings, reader! Your input is highly important to us. Please share your thoughts in the comments section below.
Contact:
Email: piyushagrawal.automation@gmail.com
Follow on LinkedIn: Piyush Agrawal - LinkedIn
Follow on YouTube: Piyush Agrawal - Youtube