Selenium Interview Questions

 1. Create a TestNG test which opens a web page with button(id=alert) clicking on which alert window opens up. Use Page Factory Implementation


Ans:

        private  By Alert =By.id("alert");      //Page Object Model

        @FindBy(id="alert") private WebElement alert;  // Page factory Model1

        @FindBy(how =How.ID,using ="alert") private WebElement alert1;  //Page factory Model2

@Test

public void test3() throws InterruptedException

{

//Code to open a page

               driver.findElement(Alert).click()   //Using Page Object Pattern

PageFactory.initElements(driver,this); //Using Page Factory Model1

alert.click();     //Using Page Factory Model2

                alert1.click()

}


2. What is CacheLookup annotation in PageFactory?

Ans:

annotation @CacheLookup to WebElements to indicate that it never changes (that is, that the same instance in the DOM will always be used)


CacheLookup attribute can be used to instruct the InitElements() method to cache the element once its located and so that it will not be searched over and over again – this is useful when the elements that are always going to be there

(For AJAX based applications, it may not work where the DOM changes based on user action on the page). Otherwise every time when we use a Web Element the WebDriver will go and search it again


Usage


@FindBy(id="alert")

@CacheLookup

private WebElement Alert;


3. How to download webdriver executables automatically?

Ans:

Add Below dependency in the Maven

<dependency>

    <groupId>io.github.bonigarcia</groupId>

    <artifactId>webdrivermanager</artifactId>

    <version>3.0.0</version>

    <scope>test</scope>

</dependency>

Note: Webdriver manager internally uses commons-io. so if you are using this, then comment it 

<!-- <dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-io</artifactId>

<version>1.3.2</version>

</dependency>-->

Usage:

private WebDriver driver;

@BeforeClass

public void setUp() {

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver();

}


4. Read all values from properties file

Ans:

File propfile = new File("propfile.properties");

FileInputStream fis = new FileInputStream(propfile);

Properties prop = new Properties();

prop.load(fis);

System.out.println(prop.get("url"));  //accessing single key value


                //Accessing all key values

Enumeration keyvalues = prop.keys();

while(keyvalues.hasMoreElements())

{

String key=(String)keyvalues.nextElement();

String value = prop.getProperty(key);

System.out.println("Key:="+key + "Value:="+value);

}


5. Difference between Exception and Error?Example for each

Ans:

Error:

public class HelloWorld{

     public static void main(String []args){

        test(5);

     }     

     public static void test(int i)

    {

        if (i == 0)

            return;

        else {

            test(i++);

        }

    }

}

Output: 

Exception in thread "main" java.lang.StackOverflowError

at HelloWorld.test(HelloWorld.java:14)

at HelloWorld.test(HelloWorld.java:14)

at HelloWorld.test(HelloWorld.java:14)

Exception:

class xception{ 

    // main driver method

    public static void main(String[] args)

    {

        int a = 5, b = 0; 

        // Try-catch block to check and handle exceptions

        try {

            // Attempting to divide by zero

            int c = a / b;

        }

        catch (ArithmeticException e) { 

            // Displaying line number where exception occured

            // using printStackTrace() method

            e.printStackTrace();

        }

    }

}

Output:

java.lang.ArithemeticException: /Zero at Xception.main


6. Selenium Architecture


There are four components of Selenium Architecture:

Selenium Client Library
JSON Wire Protocol over HTTP
Browser Drivers
Browsers

Selenium Client Libraries/Language Bindings:
Selenium supports multiple libraries such as Java, Ruby, Python, etc., Selenium Developers have developed language bindings to allow Selenium to support multiple languages. Check out Selenium Libraries in the official site.

JSON WIRE PROTOCOL Over HTTP Client:
JSON stands for JavaScript Object Notation. It is used to transfer data between a server and a client on the web. JSON Wire Protocol is a REST API that transfers the information between HTTP server. Each BrowserDriver (such as FirefoxDriver, ChromeDriver etc.,)  has its own HTTP server.

Browser Drivers:
Each browser contains separate browser driver. Browser drivers communicate with respective browser without revealing the internal logic of browser’s functionality. When a browser driver is  received any command then that command will be executed on the respective browser and the response will go back in the form of HTTP response.

Browsers:
Selenium supports multiple browsers such as Firefox, Chrome, IE, Safari etc.,
Let’s see how Selenium WebDriver works internally
In real time, you write a code in your UI (say Eclipse IDE) using any one of the supported Selenium client libraries (say Java).

Example:

WebDriver driver  = new FirefoxDriver();
driver.get(https://www.testing.com)

Once you are ready with your script, you will click on Run to execute the program. Based on the above statements, Firefox browser will be launched and it will navigates to softwartestingmaterial website.
Here we see what will happen internally after you click on Run till the launch of Firefox browser.


Once you click on Run, every statement in your script will be converted as a URL with the help of JSON Wire Protocol over HTTP. The URL’s will be passed to the Browser Drivers. (In the above code, we took FirefoxDriver). Here in our case the client library (java) will convert the statements of the script to JSON format and communicates with the FirefoxDriver. URL looks as shown below.

https://localhost:8080/{"url":"https://www.testing.com"}

Every Browser Driver uses a HTTP server to receive HTTP requests.  Once the URL reaches the Browser Driver, then the Browser Driver will pass that request to the real browser over HTTP. Then the commands in your selenium script will be executed on the browser.
If the request is POST request then there will be an action on browser
If the request is a GET request then the corresponding response will be generated at the browser end and it will be sent over HTTP to the browser driver and the Browser Driver over JSON Wire Protocol and sends it to the UI (Eclipse IDE).
This is all about Selenium WebDriver Architecture.

7. Stale Element Exception
Ans:
Element is no longer attached to the DOM
or Element has been deleted entirely
Solution1: Do a page refresh
driver.navigate().refersh();
driver.findElement(By.xpath("xpath here")).click();
Solution2: Try Catch Block
for(int i=0; i<=2;i++){
  try{
     driver.findElement(By.xpath("xpath here")).click();
     break;
  }
  catch(Exception e){
     Sysout(e.getMessage());
  }
}
Solution3:ExpectedConditions.Refreshed
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("table")));
wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf("table")));

Solution4:Using POM design pattern
initElements()
Example:
Write a selenium code to click an element
WebElement element=driver.findElement(By.xpath("xpath"));
element.click();
driver.navigate().back();
element.click()

7. SSL Certificate Handling
Example for practice:
https://badssl.com/
https://expired.badssl.com/

@Test
public void sslcertificate() {
WebDriverManager.chromedriver().setup();

driver = new ChromeDriver();
// Create instance of ChromeOptions Class
ChromeOptions handlingSSL = new ChromeOptions();

// Using the accept insecure cert method with true as parameter to accept the
// untrusted certificate
handlingSSL.setAcceptInsecureCerts(true);

// Creating instance of Chrome driver by passing reference of ChromeOptions
// object
WebDriver driver = new ChromeDriver(handlingSSL);
driver.get("https://expired.badssl.com/");
System.out.println("The page title is : " + driver.getTitle());
               
// driver.quit();

}
Note: if we dont handle ssr, titile would be privacy Error, else it would be "expired.badssl.com"

7. How to handle the below scenario
https://the-internet.herokuapp.com/basic_auth








example1:

 driver.get("https://username:password@dreamshop.honda.com/s")

example2: 

String URL = "https://" +username +":" +password +"@"+ "the-internet.herokuapp.com/basic_auth";driver.get(URL);

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


8. What is the difference between ChromeOptions and DesiredCapabilities?

ChromeOptions is a class that can be used to manipulate capabilities specific to ChromeDriver. 

For instance, you can disable Chrome extensions with:

ChromeOptions options = new ChromeOptions()

options.addArgument(“disable-extensions”);

ChromeDriver driver = new ChromeDriver(options);


DesiredCapabilities can also be used to manipulate a ChromeDriver session.

To change individual web driver properties, DesiredCapabilities class provides key-value pairs.

But, ChromeOptions supports limited clients whereas DesiredCapabilities supports a vast number of clients. 

ChromeOptions is supported by Java and other languages. 

DesiredCapabilities is available in Java, 

but its use is deprecated.

When working with a client library, like Selenium Ruby Client,

the ChromeOption class will not be available and DesiredCapabilities will have to be used.


9. Opening Browser in Incognitor window


Chrome:


DesiredCapabilities capabilities = DesiredCapabilities.chrome();

ChromeOptions options = new ChromeOptions();

options.addArguments("incognito");

capabilities.setCapability(ChromeOptions.CAPABILITY, options);

FireFox:


FirefoxProfile firefoxProfile = new FirefoxProfile();    

firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);

Internet Explorer:


DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();

capabilities.setCapability(InternetExplorerDriver.FORCE_CREATE_PROCESS, true); 

capabilities.setCapability(InternetExplorerDriver.IE_SWITCHES, "-private");

Opera:


DesiredCapabilities capabilities = DesiredCapabilities.operaBlink();

OperaOptions options = new OperaOptions();

options.addArguments("private");

capabilities.setCapability(OperaOptions.CAPABILITY, options);

Comments

Popular Posts