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.



JAVA
1.           What is abstraction?
·   Abstraction is a process of hiding the implementation details and showing only functionality to the users.
·   A class that is declared as abstract is known as abstract class. It needs to be                                  extended and its method implemented. It cannot be instantiated, but they can be        used as subclass.
·   An abstract class may or may not include abstract methods

2.           What is interface?
·                     Interface is a blueprint of a class that has static constants and abstract methods.             It can be used to achieve fully abstraction and multiple inheritance
·                     An interface is a collection of abstract methods.
·                     If a class is implementing an interface, that means the class is using abstract             methods of     the interface.

3.           Life cycle of thread?
·                     A thread can be in one of the five states. According to sun, there are only 4 states             in thread life cycle in java new, runnable, non-runnable and terminated. There             is no running state. But for better understanding the threads, we are explaining             it in the 5 states.
                     The life cycle of the thread in java is controlled by JVM. The java thread states are            as follows:
1.                  New
2.                  Runnable
3.                  Running
4.                  Non-Runnable (Blocked)
5.                  Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.

4.           Difference between interface & abstract?
Abstract class
1.     An abstract class can have method body (non-abstract methods).
2.     An abstract class can have instance variables.
3.     An abstract class can have constructor.
4.     An abstract class can have static methods.
5.     You can extends one abstract class.

Interface
1.      Interface have only abstract methods.
2.      An interface cannot have instance variables.
3.      Interface cannot have constructor.
4.      Interface cannot have static methods.
5.      You can implement multiple interfaces.

·   The main difference is, methods of interface are implicitly abstract but cannot have    implementations.
·   Variables declared in a java interface are by default final.
·   An abstract class can have an instance method that implements a default behavior.
·   An abstract class may contain non final variables.

5.           When we create a new it will be in new state, then how to make it runnable state          in threads?
·         By starting the new method we can make new as runnable.
·         For example
·         Thread1  t = new Thread1();       //new thread is created
st.start ();                                        //new thread is started and goes to runnable state

6.           Can we start java thread twice on same instance ?

·   No, we cannot start a thread twice on the same instance of a thread. It is illegal to call start() method of a thread class twice on same instance of a thread. On first call of start() method thread will start working properly but on the second call of start() method IllegalThreadStateException will be thrown.
7.           what is collections class? Difference between collection&collections?

·   Collections in java is a framework that provides an architecture to store and manipulate
the group of objects.
·   Java Collection simply means a single unit of objects.
·   Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

8.           Difference between between  Arraylist & vector?

Arraylist
·   Java ArrayList class uses a dynamic array for storing the elements.It extends    AbstractList class and implements List interface.
·   Java ArrayList class can contain duplicate elements.
·   Java ArrayList class maintains insertion order.
·   Java ArrayList class is non synchronized.
·   Java ArrayList allows random access because array works at the index basis.
·   In Java ArrayList class, manipulation is slow because a lot of shifting needs to be    occurred if any element is removed from the array list.
linked list
·   Java LinkedList class uses doubly linked list to store the elements. It extends the                      AbstractList class and implements List and Deque interfaces.
·   Java LinkedList class can contain duplicate elements.
·   Java LinkedList class maintains insertion order.
·   Java LinkedList class is non synchronized.
·   In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
·   Java LinkedList class can be used as list, stack or queue.
ArrayList
LinkedList
1) ArrayList internally uses dynamic array to store the elements.
LinkedList internally uses doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
3) ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.


ArrayList
Vector
1) ArrayList is not synchronized.
Vector is synchronized.
2) ArrayList increments 50% of current array size if number of element exceeds from its capacity.
Vector increments 100% means doubles the array size if total number of element exceeds than its capacity.
3) ArrayList is not a legacy class, it is introduced in JDK 1.2.
Vector is a legacy class.
4) ArrayList is fast because it is non-synchronized.
Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.
5) ArrayList uses Iterator interface to traverse the elements.
Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

9.           Difference between super & this
·         Super 

 1.used to access the super class member 
syntax:-
super.show(); 
super.x; 
2.used to sent the loan argument from sub class to super class constructor 
syn:-super(arg1,arg2); 
·          
·         this 

1.refer the current class object 
syn:-this.x=x; 
2.used to sent the argument in same class constructor 
syn:-this(arg1.arg2);


10.      Difference between SVN & GIT server?
·         svn- server having only commit  it will upload in the server
·         GIT- commit,push
·         commit- it will not effect to remote system
·         push-it will effect to remote system. In remote system, it is also updated.

11.      Difference between Commit &push?
·         Well, basically git commit puts your changes into your local repository, while git push sends your changes to the remote location. Since git is a distributed version control system, the difference is that commit will commit changes to your local repository, whereas push will push changes up to a remote repo
·         commit- it will not effect to remote system
·         push-it will effect to remote system. In remote system it also updated.

12.      What is overloading & overriding?
·         Method Overloading:
·         If a class has multiple methods by same name but different parameters, it is known as Method Overloading.
·         In java, method overloading is not possible by changing the return type of the method.
·         Method overloading increases the readability of the program.
·         There are two ways to overload the method in java
§  By changing number of arguments
§  By changing the data type
§   
·         Method overriding:
·         If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
·         In other words if the sub classes has the same method of the parent class with different implementation, it is known as method overriding.
·         It is used for runtime polymorphism.

Rules for Java Method Overriding

1.      Method must have same name as in the parent class
2.      Method must have same parameter as in the parent class.
3.      Must be IS-A relationship (inheritance).
13.      What kind of Exception u faced
·         nosuchelement():Element may not yet be on the screen at the time of the find operation.
·         nosuchalert(): when an alert is not yet on the screen.
·         nullpointer():If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
Example:
String s=null;
System.out.println(“length of s is ”+s.length());
·         nosuchwindow():  Is thrown when window target to be switched doesn’t exist.

14.      Hierarchy of exception?

15.      throw &  throws
·         throw:  throw keyword is used to explicitly throw an exception.
·         The throw keyword is mainly used to throw custom exception.
·         We can throw either checked or uncheked exceptions in java by throw keyword.
·         throws: The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
·         Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
16.      what is constructor?
·            Constructor in java is a special type of method that is used to initialize the object.
            Java constructor is invoked at the time of object creation. It constructs                 the values   i.e. provides data for the object that is why it is known as                   constructor.

17.      what is the return type of constructor
·                        Constructors have no return type, not even void.

18.      what is static keyword?
        ·      The static keyword denotes that a member variable, or method, can                              be accessed without requiring an instantiation of the class to which it                            belongs. In simple terms, it means that you can call a method, even if                               you've never created the object to which it belongs!
       ·       Static variables are initialized only once , at the start of the execution .                             These variables will be initialized first, before the initialization of any                           instance variables
       ·        A static variable can be accessed directly by the class name and doesn’t                         need any object

19.      why string class immutable?
·     String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.



Sorry if you feel any inconvie

12 comments:

  1. Amazing, thanks a lot my friend, I was also siting like a your banner image when I was thrown into Selenium.When I started learning then I understood it has got really cool stuff.
    I can vouch webdriver has proved the best feature in Selenium framework.Thanks a lot for taking a time to share a wonderful article.
    Best Selenium Training Institute in Chennai | Selenium Training in Velachery

    ReplyDelete
  2. It will be really helpful for selenium candidates and nice to visit your blog. Thanks a lot.

    Selenium Training in Pune

    ReplyDelete
  3. Even a fresher can gain more knowledge here and helpful blog to those who need to prepare about selenium & java for their next interview.

    Contact Devolve - Web Development Company in Calgary for your any web development needs.

    ReplyDelete
  4. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience.
    Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in


    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  5. Helpful blog to those who are searching to start their career in Java or Selenium field. The QA which you shared is knowledgeable.

    Jeevitha
    Way2Smile

    ReplyDelete
  6. Good insight for the beginners to effectively learn about Java or Selenium field. Expecting more Related Blogs like this.

    Best Regrads - VigneshWaran P ( java App Development Companies)

    ReplyDelete
  7. Wonderful thanks for sharing an amazing idea. keep it...

    Looking for Software Training in Bangalore , learn from Softgen Infotech Software Courses on online training and classroom training. Join today!

    ReplyDelete
  8. your article was excellent am seeing a long time one of the good blogs.
    promotional sms chennai
    sms marketing chennai


    ReplyDelete