Automation Using Selenium Webdriver

Thursday, 20 October 2016

Selenium Java Interview Questions

Selenium Java Interview Questions

Caught Exception and Uncaught exception

Caught Exception:
When the programmer is not liable for error, Error come in run time, after execution.
Ex: int i =5/0;

Uncaught Exception:
When programmer is liable for error. Error comes at the time of programming.
Ex:
Thread.sleep(5000L);
---------------------------------------------------------------------------------------------------------
Difference between "Add throws declaration" and Surround with Try/Catch

Add throws declaration: If we don't want to report the error than we use this function.

Surround with Try/Catch block: If we want to report the error in selenium report than we use this function.
---------------------------------------------------------------------------------------------------------

Difference between Throws and Throw

Throws: Throws come in front of function and it tells Java that this function is capable of throwing an exception.
Ex: Add throws declaration" or Surround with Try/Catch

Throw: Throw clause is used to deliberately through an exception.
---------------------------------------------------------------------------------------------------------

Difference between final and finally

final: Stats that you cannot change the value of variable.
Ex: final int s=100; // Cannot change the value
        //s =101;  //it will give error

finally: finally is used with try/catch block. Finally stats that (finally is a block) it will executed for sure weather try block or catch block is executed or not.
Ex: try{
    //establish DB connection
    //fire query
    //get results
    //close connection
    }catch{Exception e}
    {
    //error
    System.out.println("error");
    }finally{
    //close the connection if established
    System.out.println("is finally");
    }
---------------------------------------------------------------------------------------------------------
Difference between Error and Exception:
Error: Out of memory error, ex: Assertion error thrown, when running the eclipse sometimes when run big program when error comes eclipse gone out of memory error.
Exception: run time exception, null pointer exception; divide by zero exception, array index out of bond etc.
---------------------------------------------------------------------------------------------------------
String to Integer Conversion:
String x = 100;
int 1 = Integer.parseInt (x);

int is the primitive data type but Integer is an in build  class just like a String class which represent int.
---------------------------------------------------------------------------------------------------------
Integer to String Conversion:
String z = String.valueof(i);
---------------------------------------------------------------------------------------------------------
String to Boolean conversion:
boolean b = Boolean.valueof("true");
https://mail.google.com/mail/u/0/images/cleardot.gif
---------------------------------------------------------------------------------------------------------
Collection API: Array List and Hash table are collection API.

ArrayList is similar to Array but it is not an array, it is inbuilt class and it is dynamically growing in size.

Ex: It is used where we need to read/get bulk data from site, get data from popup etc.
ArrayList <String> list = new ArrayList <String>();
        list.add("A");
        list.add("B");
        list.add("C");
        System.out.println(list.size());
for(int i =0;i<list.size();i++)
        {
            System.out.println(list.get(i));
        }

---------------------------------------------------------------------------------------------------------
Hah table and array list both are dynamically growing data structure. whereas Array List grow with index and Hash table grows with Kay and Value pair.
---------------------------------------------------------------------------------------------------------
HashTable: Hashtable is inbuilt class we can create object of the class. Hashtable contains key value pair (key and value). Key should be unique and corresponding to each key there should be a value.
Ex: We used Hash table to store test data.

Hashtable <String, String> table = new Hashtable <String, String>();
        table.put("Name", "Sunil");
        table.put("Company", "InfoBeans");
        table.put("Place","Indore");
        System.out.println("------------ Hash Table ----------");
        System.out.println(table.get("Name"));

Verify Image Presence in Web Page using Selenium WebDriver


JavaScript executor is one of themost useful features of Selenium WebDriver. It allows Selenium user to perform many complex scenarioseasily. This post covers one such important scenario.Selenium verify image present example using WebDriver. We have used JavaScript executor in WebDriver Java code hereto verify if image is present in a web page.


@Test
public void CheckImage() throws Exception {
driver.get(baseUrl);
WebElement ImageFile = driver.findElement(By.xpath("//img[contains(@id,'Test Image')]"));
        
        Boolean ImagePresent = (Boolean) ((JavascriptExecutor)driver).executeScript("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", ImageFile);
        if (!ImagePresent)
        {
             System.out.println("Image not displayed.");
        }
        else
        {
            System.out.println("Image displayed.");
        }
}
Run your test. It should identify if image is displayed in web page and will print appropriate result in console

Page Object Model(SingIn-Page)Exp

By Using Page Object Model SignInPage  Store Locaters and Test  Best Example for (Singin-Page)

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

/**
 * Class which models the view of Sign-In page
 */
public class SignInPage {
 
    @FindBy(id="username")
    private usernameInput;

    @FindBy(id="password")
    private passwordInput;

    @FindBy(id="signin")
    private signInButton;

    private WebDriver driver;

    public SignInPage(WebDriver driver) {
        this.driver = driver;
    }
 
    /**
     * Method to perform login
     */
    public HomePage performLogin(String username, String password) {
        usernameInput.sendKeys(username);
        passwordInput.sendKeys(password);
        signInButton.click();
        wait.ForPageToLoad();
        return PageFactory.initElements(driver, HomePage.class);
    }
}


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
/**
 * Class which models the view of home page
 */
public class HomePage {
    @FindBy(id="logout")
    private logoutLink;

    private WebDriver driver;

    public HomePage(WebDriver driver) {
        this.driver = driver;
    }
 
    /**
     * Method to log out
     */
    public SignInPage logout() {
        logoutLink.click();
        wait.ForPageToLoad();
        return PageFactory.initElements(driver, SignInPage.class);
    }
}

/**
 * Login test class
 */
public class LoginTest {
    public void testLogin() {
        SignInPage signInPage = new SignInPage(driver);
        HomePage homePage = signInPage.login(username, password);
        signInPage = homePage.logout();
    }
}

Challenges faced while working on Selenium

Challenges faced while working on Selenium

There are many challenges we face while working on selenium. Some of the challenges are:

Challenges faced that are as follows:
·         Frequently changing UI. It always need to make changes in code most of the time.
·         Stuck somewhere while running automation scripts in chrome browser getting error that element is not visible, element not found.
·         New kind of element like ck-editor, bootstrap calendar and dynamic web tables. But get the solution always.
·         Reused of test scripts.
·         To be continued

1. configuration challenges on different machines
2. selenium's compatibility with browser versions like with FF20 is not supported with some web-driverversions.
3. handling IE/chrome etc.
4. popup handling
5. Ajax handling
6. security certificate handling
7. iframes
8. date pick from calender.
9. identifying locators
10. Upload and download file
11. Maintain the scripts to work properly irrespective of new build
12. Diff to identify script has failed may be unable to locate the element
or config issue(Browser updated) if your framework is not able to catch issue.
13. If you are using xpath as a locator. writing xpath without using dynamic changing data.
i.e., xpath generated dynamically.

Enter a text without using SendKeys method() in Selenium Webdriver

How to Send text without using sendkeys methods

public class type{

public static void setattribute(WebElement element,String attributename,String Value){

WrapsDriver wrappedElement=(WrapsDriver)element;
JavascriptExecuter driver =(JavaScriptExecutor)wrappedElement.getWrapedDriver;
driver.executeScript(arguments[0].setAttribute(arguments[1],arguments[2]",element,
                                    attributeName,value);
}

//or

JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('email').value = 'thotajagan@gmail.com';");


Onemore Example:

driver.get("http://facebook.com/");
WebElement cssValue= driver.findElement(By.xpath(".//*[@id='s']"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('s').value='Virender Testing   
sending'");