Friday 19 August 2016

Selenium and Java Interview Questions

Hi QA Friends,

These are the frequently asked Selenium and Java  interview questions for freshers and experience people. I hope, it will help you for your interview. we will be updating more questions soon...



1.           What are your Roles & Responsibilities?
·         Identify Test cases for Automation.
·         Developing methods for repeating steps.
·         Writing scripts, executing test cases and debugging.
·         Prepare automation scripts in Selenium WebDriver.
·         Designing Automation Framework and Implementing Automation Framework.
·         Regression Testing, support and reviewing Test scripts.
·         Data driving Test script.
·         Defect reporting, Executing Framework and Analyzing Result.

                                                     
2.           What is hybrid framework?  what is combination of it?

·      Hybrid is a combination of data driven and keyword driven            framework.
·     Keyword driven framework : It enable the tester to create its own customized keyword         which can be used while automating the application.
·     Data driven framework : It enables the tester to fetch data from an external source such    as DB, even from an excel sheet.
·     The framework, which integrates the above two, is known as Hybrid framework.

3.           how u generate reports?
·         Generate XSLT Report(Advanced HTML Report) in selenium
·         XSLT stands for XML style-sheet language for transformation, it provide very rich formatting report using TestNG framework
·         Precondition:
·         Ant should be installed if not please install using below post
·         install ANT
·         At least one testcase should be executed by TestNG (i.e we should have test-output directory available in home directory)
Step 1-Download XSLT from


step 2-unzip this copy all the files and paste into project home directory. Add all files into project, ‘not under src folder’

step 3-Run build.xml using Ant – To run build.xml file
To check whether the ‘ant’ installed properly or not
Open CMD and go till project directly and type ‘ant’ run and hit enter.
To generate xslt reports using cmd prompt
Open cmd prompt, go to project folder, ‘not in src folder’ and type ‘ant generateReport’ and hit enter.
Step 4-once build successful then type ‘ant generateReport’ and hit enter again
Step 5-once build successful then go to project directory and you will get testing-xslt folder
Inside testing-xslt you will get index.html (this is the main report) open in FF or in chrome



4.           How you manage test data? How can u read  data?
·         We have managed testdata by using data driven framework or hybrid driven             framework .
·         By using xls reader we read the data
·         To achieve the test data we need to write the below program in a separate class.


import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.concurrent.TimeUnit;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;

import com.google.common.base.Verify;

public class Read_data_from_xl_POI
{
     static WebDriver d;
public static void main(String[] args) throws Exception {
   
    d=new FirefoxDriver();
    d.get("http://gmail.com");
   
    File src=new File("D:\\selenium_NEW_PRACTICE\\test_data\\read_excel_data_test.xls");
    FileInputStream fis=new FileInputStream(src);
    HSSFWorkbook wb= new HSSFWorkbook(fis);
    HSSFSheet sheet1=wb.getSheetAt(0);



//imp note: For xl file use : HSSF
//for .xlsx file use: XSSF
   
    int totalRowCount=sheet1.getLastRowNum();
    System.out.println("total rows is:" + totalRowCount);
   
    String firstRowName=sheet1.getRow(0).getCell(0).getStringCellValue();
    System.out.println("first row first column name is: " + firstRowName);
   
    String secondColFirstName=sheet1.getRow(0).getCell(1).getStringCellValue();
    System.out.println("first row first column name is: " + secondColFirstName);
   
    //for print all the rows usng for loop
   
    for(int i=0;i<totalRowCount;i++)
    {
        String userName=sheet1.getRow(i).getCell(0).getStringCellValue();
        System.out.println("first row all names:" + userName);
       
        String passwordName=sheet1.getRow(i).getCell(1).getStringCellValue();
        System.out.println("first row all names:" + passwordName);
       

/*d=new FirefoxDriver();
d.get("http://gmail.com");*/
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
d.findElement(By.xpath("//*[@id='Email']")).sendKeys(userName);
d.findElement(By.xpath("//*[@id='next']")).click();

d.findElement(By.xpath("//*[@id='Passwd']")).sendKeys(passwordName);
d.findElement(By.xpath("//*[@id='signIn']")).click();
String actErrorMsg=d.findElement(By.xpath("//*[@id='errormsg_0_Passwd']")).getText();
String expErrorMsg="The email and password you entered don't match.";
System.out.println("actual message is: " +actErrorMsg);

//Assert.assertEquals("The email and password you entered don't match.", actErrorMsg);

if(expErrorMsg.contains(actErrorMsg))
        {
    System.out.println("sucess");
        }else
            System.out.println("not sucess");
d.navigate().back();

    }
}


5.           why are you using data provider ,How?
·         @DataProvider    Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ] where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
·         A DataProvider is data feeder method defined in your class that supplies a test method with data .
·         The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method.
  Example Script:

@DataProvider(name = "DP1")
public Object[][] createData() {
Object[][] retObjArr={{"001","Jack","London"},
                                      {"002","John","New York"},
                                                   {"003","Mary","Miami"},
{"004","George","california"}};
return(retObjArr);
    }

@Test (dataProvider = "DP1")
public void testEmployeeData(String empid, String empName, String city){
selenium.type("id", empid);
selenium.type("name", empName);
selenium.click("submit_button");
selenium.waitForPageToLoad("30000");
assertTrue(selenium.isTextPresent(city)); }

6.           In your project have you used cross-browser types? How u implement it?
·         By using selenium grid we do cross-browsing testing
·         we create config.properties

if(driver==null)
{
CONFIG= new Properties();
FileInputStream fn=new FileInputStream(System.getProperty("user.dir")+"\\src\\com\\selenium\\config\\config.properties");
//src\com\selenium\config\config.properties
CONFIG.load(fn);

OR=new Properties();
fn=new FileInputStream(System.getProperty("user.dir")+"\\src\\com\\selenium\\config\\OR.properties");
//src\com\selenium\config\config.properties
OR.load(fn);

if(CONFIG.getProperty("browser").equals("Firefox")){
dr = new FirefoxDriver();
}
else if(CONFIG.getProperty("browser").equals("Chrome")){
System.setProperty("webdriver.chrome.driver", "D:\\chrome\\chromedriver.exe");
dr = new ChromeDriver();
}
else if(CONFIG.getProperty("browser").equals("IE")){
System.setProperty("webdriver.IE.driver", "D:\\IE\\IE.exe");
dr = new InternetExplorerDriver();
}



7.           What are different ways in which you can generate the reports of TestNG results?

·         Listeners: For implementing a listener class, the class has to implement the org.testng.ITestListener interface. These classes are notified at runtime by TestNG when the test starts, finishes, fails, skips, or passes.
·         Reporters: For implementing a reporting class, the class has to implement an org.testng.IReporter interface. These classes are called when the whole suite run ends. The object containing the information of the whole test run is passed to this class when called.


8.           what is POM?

·         Within your web app's UI there are areas that your tests interact with. A Page Object simply models these as objects within the test code. This reduces the amount of duplicated code and means that if the UI changes, the fix need only be applied in one place.

9.           What is TestNG?

·         Annotation    Description
@BeforeSuite    The annotated method will be run only once before all tests in this suite have run.
@AfterSuite    The annotated method will be run only once after all tests in this suite have run.
@BeforeClass    The annotated method will be run only once before the first test method in the current class is invoked.
@AfterClass    The annotated method will be run only once after all the test methods in the current class have been run.
@BeforeTest    The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
@AfterTest    The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.
@BeforeGroups    The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroups    The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@BeforeMethod    The annotated method will be run before each test method.
@AfterMethod    The annotated method will be run after each test method.
@DataProvider    Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ] where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
@Factory    Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ].
@Listeners    Defines listeners on a test class.
@Parameters    Describes how to pass parameters to a @Test method.
@Test    Marks a class or a method as part of the test.

10.      How u retrieve the data from database?

String Driver="com.mysql.jdbc.Driver";
//Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:mysql://localhost:3306/selenium";
//"jdbc:mysql://localhost:3036/selenium";

//Database Username
String username = "root";

//Database Password
String password = "mysql";

//Query to Execute
String query = "select *  from emp;";

//Load mysql jdbc driver
Class.forName(Driver);


//Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl,username,password);

//Create Statement Object
Statement stmt = con.createStatement();

// Execute the SQL Query. Store results in ResultSet
ResultSet rs= stmt.executeQuery(query);

// While Loop to iterate through all data and print results
while (rs.next()){
String name = rs.getString(1);
String design = rs.getString(2);
int sal=rs.getInt(3);
System. out.println(name+"    "+design+"     "+sal);
}
// closing DB Connection
con.close();

11.      what is jenkins?

·         Jenkins is one open source tool to perform continuous integration.
The basic functionality of Jenkins is to monitor a version control system and to start and monitor a build system (for example, Apache Ant or Maven) if changes occur.
Jenkins monitors the whole build process and provides reports and notifications to alert maintainers on success or errors.

12.      what kinds of webelement u across?

   ·         By id, by name, by classname, by tagname, by xpath, by linktext, by                                  partialTextlink, by cssselector.

13.      how to handle the mouseover action commands?

Actions a=new Actions(driver);
//mouse action
WebElement str=driver.findElement(By.linkText("About Us"));
a.moveToElement(str).build().perform();

14.      how to handle dropdown?
·         You have to make the object select class and supply the webelement which we have selecting
·         Select  sel=new select(driver.findElement(by.xpath(“”)));
·         Sel.selectbyvalue(“”);
·         Sel.selectbyindex(8);
·         Sel.selectbyvisibleText(“Test”);
·         List<webelement>  l=sel.getoption();

15.      how t handle frame?
·         driver.switchTo.frame(name or id)
·         driver.switchTo.frame(index)

16.      How to take screenshot?
·         Directly we cannot get a screenshot in selenium
·         We have to cast  the driver to take a screen shot  class
·         File screenshot = ((Takescreenshot)driver).getScreenshotAs(OutputType.FILE);
·         Fileutils.copyFile(screenshot, new File(“ file path ”));

17.      how to generate dynamic xpath?
·         start-with() :
If your dynamic element’s id’s have the format where button id=”continue-12345” where 12345 is a dynamic number. You can use the following
 Xpath:
//button[start-with(@id,’continue-’)]

·         Contains() :
Sometimes an element gets indentified by a value that could be surrounded by other text, then contains() can be used.
To demonstrate, the element can be located based on the ‘suggest’ class without having to couple it with the ‘top’ and ‘business’ classes using the following
Xpath:
//input[contains(@class, ‘suggest’)]
 For example:

driver.findElement(By.xpath("//*[contains(@id,'select2-result-label-535')]").click();


18.      How to send the data in textbox?
·         By using
Driver.findelement(by.xpath)).sendkey(“”);

19.      What kind of Exception u faced ?
·         In one of a situation like where you have got an exception and you want to print some custom message in your logs, so that it can be understandable by the whole team.
·         In some situations where you want to just take up the exception and want you test to carry on with rest of the code/script execution.

Some different exceptions are mentioned below:

1) NoSuchElementException : FindBy method can’t find the element.
2) StaleElementReferenceException : This tells that element is no longer appearing on the      DOM page.
3) TimeoutException: This tells that the execution is failed because the command did not complete in enough time.
4) ElementNotVisibleException: Thrown to indicate that although an element is present on the DOM, it is not visible, and so is not able to be interacted with


5) ElementNotSelectableException: Thrown to indicate that may be the element is disabled, and so is not able to select.