QA Interview: Top 70: Selenium With Java Interview Questions (36:70)

 Other Useful Links:



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);


37. JavaScriptExecutor is class or 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.


39. Name few exception in Selenium

  • 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.


  1. getBrowserName()

  2. setBrowserName()

  3. getVersion()

  4. setVersion()

  5. getPlatform()

  6. setPlatform()

  7. getCapability()

  8. setCapability()

Example:

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");

capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);


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();

}

}


42. TakeScreenShot is class or 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.


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).


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();

}

}


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.

  1. alertIsPresent()

  2. elementSelectionStateToBe()

  3. elementToBeClickable()

  4. elementToBeSelected()

  5. frameToBeAvaliableAndSwitchToIt()

  6. invisibilityOfTheElementLocated()

  7. invisibilityOfElementWithText()

  8. presenceOfAllElementsLocatedBy()

  9. presenceOfElementLocated()

  10. textToBePresentInElement()

  11. textToBePresentInElementLocated()

  12. textToBePresentInElementValue()

  13. titleIs()

  14. titleContains()

  15. visibilityOf()

  16. visibilityOfAllElements()

  17. visibilityOfAllElementsLocatedBy()

  18. 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();

}

}


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);


49. Implicit Wait vs Explicit Wait

Implicit Wait

Explicit Wait

All elements on the page have an implicit wait time.

Explicit wait is applied to only those elements which are intended by us.

In Implicit wait we don't need to specify conditions on elements.

In Explicit wait, we need to specify ExpectedConditions on an element. 

It is simple and easy to implement

In comparison to implicit wait, it is more difficult to implement.

It does not catch any performance issue in the application.

It can catch performance issue in the application

Because each step waits for this delay until it finds the element it is looking for, it slows down the execution pace.

It does not affect the execution speed since it is applied to a particular element.

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.

  1. clickAndHold(): Clicks at the current mouse position (without releasing it).

  2. contextClick(): Performs Right Click Mouse Action

  3. doubleClick():  Double-clicks where the mouse is currently positioned.

  4. 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.

  5. keyDown(modifier_key): Performs a modifier key press. If the modifier key is not released, future interactions may presume it is still pressed.

  6. moveByOffset(x-offset, y-offset): Moves the mouse by the supplied offset from its present position (or 0,0).

  7. moveToElement(toElement): Moves the mouse to that element.

  8. release(): Releases the depressed left mouse button at the current mouse location

  9. 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();

        }

}


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:

  1. 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.

  2. 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.

  3. Because of the reusable page methods in the POM classes, code gets less and more optimised.

  4. 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

  1. Page Factory is a Selenium WebDriver inherent Page Object Model framework concept that is highly efficient.

  2. In addition, we use annotations @FindBy to find WebElement using Selenium's PageFactory class.

  3. As attributes, @FindBy accepts tagName, partialLinkText, name, linkText, id, css, className, and xpath.

  4. Syntax: @FindBy(id="elementId") WebElement element;

  5. Page Factory - page object design pattern uses AjaxElementLocatorFactory to identify WebElements only when they are utilised in any operation.

  6. 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

POM

Page Factory

It is an approach for design pattern

It is a class provided by selenium webdriver

It aids in the separation of page items from scripts.

It is a technique to implement POM

Page objects are defined using 'By' annotations.

@FindBy annotation is used to define page objects


There is a cache storage to perform tasks

There is no need for cache storage

POM does not provide lazy initialization

Page Factory provide lazy initialization

Need to initialize page objects individually

All page objects are initialized using initElements() method.

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:

  1. Declare constructor of class as private.

  2. Declare a static reference variable of class. To make it available globally, static is required.

  3. 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.


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.

  1. Object Repository using Properties file

  2. 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();

  }

}


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.


63. How To Change Default Download Directory For Chrome Browser In Selenium WebDriver

import java.io.*;;
import java.util.*;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
 
public class ChangeDownloadDirOfChrome {
    public static void main(String[] args){
        System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
 
        // Setting new download directory path
        Map<String, Object> prefs = new HashMap<String, Object>();
         
        // Use File.separator because it works on all operating systems.
        prefs.put("download.default_directory",System.getProperty("user.dir") + File.separator + "externalFiles" + File.separator + "downloadFiles");
         
        // Adding cpabilities to ChromeOptions
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);
         
        // Printing set download directory
        System.out.println(options.getExperimentalOption("prefs"));
         
        // Launching browser with desired capabilities
        ChromeDriver driver= new ChromeDriver(options);
         
        // URL loading
        driver.get("https://www.seleniumhq.org/download/");
         
        // Download the selenium server jar file.
        driver.findElement(By.xpath("//p[text()='Download version ']/a")).click();
    }
}


64. How to launch a batch file from Selenium?

Process batch = Runtime.getRuntime.exec(PathOfBatchFile);


65. How to manage browser drivers easily (Driver-Browser compatibility)?
 
Traditional way of instantiating browsers in 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.
Why is WebDriverManager needed?

WebDriverManager is a class that lets us download and set browser driver binaries without having to manually insert them into automation scripts as developers.
  • 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.
Example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import io.github.bonigarcia.wdm.WebDriverManager;

public class WebDriverManagerDemo {
public static void main(String[] args) {
ChromeOptions chromeOptions = new ChromeOptions();
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver(chromeOptions);
driver.get("https://www.testing.com");
driver.quit();
}
}

Also, we can set up specific driver versions, architecture, proxy, proxy username and password.
Example:
WebDriverManager.chromedriver()
                 .version("83.0.0")
                 .arch32()
                 .proxy("proxyhostname:80")
                 .proxyUser("username")
                 .proxyPass("password")
.setup();


66. Database connectivity with Selenium

Example:
import  java.sql.*;
public class  SQLConnectivity {
     public static void  main(String[] args) {
                String dbUrl = "jdbc:mysql://localhost:3033/students";
String uname = "root";
String upass = "root";
String query = "select * from studentDetails;";

            Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection(dbUrl,uname,upass);
         Statement st = con.createStatement();
          ResultSet rset= st.executeQuery(query);
         
while (rset.next()){
  String Name = rset.getString(1);
                          String Age = rset.getString(2);
                          System. out.println(Name+" : "+Age);
                 }
       con.close();
}
}


67. Advance Webdriver Waits

We can make our own Advanced WebDriver Waits or Custom Waits.. A fluent wait looks like this:

FluentWait wait = new FluentWait(driver);
wait.withTimeout(5000, TimeUnit.MILLISECONDS);
wait.pollingEvery(250, TimeUnit.MILLISECONDS);
wait.ignoring(NoSuchElementException.class);

  • 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);
}

What is a Predicate?
Predicates are similar to functions in that they always return a Boolean expression.

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.MINUTES);
wait.ignoring(NoSuchElementException.class); 

Predicate<WebDriver> predicate = new Predicate<WebDriver>(){
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(predicate);
}

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

Happy to Help You !!