Selenium Java Interview Questions
Short Description
selenium interview questions...
Description
TESTING WORLD
www.thetestingworld.com
www.thetestingworld.com
Call/Whatsapp - 874391 3121
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Advantage of Selenium over QTP 1 Free (No license fees is required) 2 Support large number of browser(QTP support only 3) 3 Support large number of programming language(C#, Java, Python, Perl etc), QTP support only VB script 4 With the help of grid we can execute multiple test cases in parallel, ultimately we are saving lot of execution time, this kind of feature not available in QTP
Advantage of QTP over Selenium 1 User Friendly, Easy to work on 2 Can develop test cases in much faster way as compared to Selenium 3 Support all type of application(client-server, window , web) 4 Limited programming skills are required
Difference between Selenium IDE, RC and WebDriver
Selenium IDE
Selenium RC
Selenium WebDriver
It only works in Mozilla browser.
It supports with all browsers like Firefox, IE, Chrome, Safari, Opera etc. It doesn’t supports Record and playback Required to start server before executing the test script. It is standalone java program which allow you to run Html test suites. Core engine is Javascript based
It supports with all browsers like Firefox, IE, Chrome, Safari, Opera etc. It doesn’t supports Record and playback Doesn’t required to start server before executing the test script. It actual core API which has binding in a range of languages.
It supports Record and playback Doesn’t required to start server before executing the test script. It is a GUI Plug-in
Core engine is Javascript based Very simple to use as it is record & playback. It is not object oriented
It is easy and small API API’s are less Object oriented
It doesn’t supports of moving mouse cursors. Need to append full xpath with ‘xpath=\\’ syntax It does not support to test iphone/Android applications
It doesn’t supports of moving mouse cursors. Need to append full xpath with ‘xpath=\\’ syntax It does not support to test iphone/Android applications
Commands to Create Webdriver object for different browsers www.thetestingworld.com
Interacts natively with browser application As compared to RC, it is bit complex and large API. API’s are entirely Object oriented It supports of moving mouse cursors. No need to append full xpath with ‘xpath=\\’ syntax It support to test iphone/Android applications
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Firefox FirefoxDriver driver = new FirefoxDriver();
Chrome Driver System.setProperty("webdriver.chrome.driver", "path of chrome driver executable"); ChromeDriver driver = new ChromeDriver();
IE Driver System.setProperty("webdriver.ie.driver", "path of ie driver executable"); InternetExplorerDriver driver = new InternetExplorerDriver();
All Supported Element Locators in Selenium Element Locator
Supported in Webdriver
Supported in RC
Id
findElementById
id=
Name
findElementByName
name=
Identifier
Not Available
identifier=
Link
findElementByLinkText findElementByPartialLinkText
link=
CSS
findElementByCssSelector
css=
DOM
Not Available
dom=
XPATH
findElementByXpath
xpath=//
Class Name
findElementByClassName
class=
Tag Name
findElementByTagName
Not available
What is Annotation Annotation can be defined as metatag, which holds information about methods which are placed next to it. Unit Testing tool like Junit and TestNg support Annotations
Annotations in Junit @Test @Test (timeout=500) @Test(expected=IllegalArgumentException.class)
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
@Before : Will execute before every @Test Annotation @After : Will execute after every @Test Annotation @BeforeClass : Will execute before executing any other annotation, execute only once at the start @AfterClass : Will execute after executing all other annotation, execute only once at the end @Ignore : Used with @Test annotation, will skip execution of particular test method @Parameterized : Used for running my test case with multiple data
Order of Execution @BeforeClass → @Before → @Test → @After → @AfterClass
Annotations Supported in TestNg @Test : Marks a class or a method as part of the test. @BeforeSuite : The annotated method will be run before all tests in this suite have run. @AfterSuite : The annotated method will be run after all tests in this suite have run. @BeforeTest : The annotated method will be run before any test method belonging to the classes inside the tag is run. @AfterTest : The annotated method will be run after all the test methods belonging to the classes inside the tag have run. @BeforeGroups : The list of groups that this configuration method will run before. This method is guaranteed to run 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. @BeforeClass : The annotated method will be run before the first test method in the current class is invoked. @AfterClass : The annotated method will be run after all the test methods in the current class have been run. @BeforeMethod : The annotated method will be run before each test method. @AfterMethod : The annotated method will be run after each test method.
Order of Execution @BeforeSuite → @BeforeTest → @BeforeGroup → @BeforeClass --> @BeforeMethod @Test → @AfterMethod → @AfterClass → @AfterGroup → @AfterTest→ @AfterSuite
Difference between Junit & TestNg TestNg
Junit
Generate html reports automatically
For reports, we need to use ANT
Can generate report for test case as well as test suite
We can’t create report of 1 test case, only reports for test suites can be generated
Support more annotations than Junit, make it more flexible
Support annotation
Can set order of execution of multiple test annotation in single class file using priority
Can’t set order of execution of multiple test annotation in single class file
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Can execute particular group of test cases
No concept of group execution
TestNg.xml is very simple and easy to understand
Build.xml is complex and difficult to understand
We have option to set threads for parallel execution(used in Grid)
Can’t set multiple threads(parallel execution)
Different ways to open URL in Webdriver
get() and navigate() both are used to open URL/application in webdriver Difference is that in case of get() method, we can just open a URL while in case of navigate() method, we can use forward and back button of browser Get() method driver.get("http://rediff.com");
Navigate() method driver.navigate().to("http://rediff.com"); driver.navigate().back(); driver.navigate().forward();
Wait in Webdriver Or Ajax handling in Selenium Webdriver
1 Thread.sleep(10) Thread is a java class, we are calling sleep method of that class It will add a forcefully wait at particular point This is used when we want to always pause our execution at specific point
2 ImplicitWait Implicitly wait are mainly used when our element on page are taking some time to load It we don’t add any wait in our script, then our driver will search for element and if not found immediately failed that step In case of implicitly wait, our driver will wait for specified time(time mentioned in implicitly wait) for that element to be present This wait will be applicable for “findElements” commands only This need to placed at the start of test case, will be applied on all “findElements” commands FirefoxDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 3 Explicit Wait (WebdriverWait class) Explicitly wait (WebdriverWait class), is mainly used when we want to wait in script until a specified condition is satisfied or max timeout we have given FirefoxDriver driver = new FirefoxDriver(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.textToBePresentInElement(By.id("f_id"), "Hello")); 4 Fluent Wait It implements Wait interface and we create object of FluentWait class Here we can set maximum time we should wait for element to be present(withTimeout method) Here we can set after how much time, it will check for element to be present (pollingEvery method) Here we can ignore any exception if it comes at runtime while waiting (ignoring method)
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Wait wait = new FluentWait(driver) .withTimeout(30, SECONDS) .pollingEvery(5, SECONDS) .ignoring(NoSuchElementException.class); Working with LIST AND DROPDOWN in selenium
Selenium WEBDRIVER // To Work on dropdown or List we need to create object of Select class Select dateselect = new Select(driver.findElementById("f_mydata"));
Selenium RC // Working with List selenium.addSelection("ElementLocator", "Value"); // Working with Dropdown selenium.select("ElementLocator", "Value");
// Here we have 3 options to select an element dateselect.selectByIndex(1); dateselect.selectByValue("15"); dateselect.selectByVisibleText("MyData");
Multiple Windows handling in Webdriver
// Creating webdriver object FirefoxDriver driver = new FirefoxDriver(); driver.get("http://rediff.com"); // getWindowHandles method of driver class return //a string // this string is a unique key referencing all //browsers/opend by our webdriver, //we save all values in a Set Set hs = driver.getWindowHandles(); // Iterating to the set and picking all available values Iterator iter = hs.iterator(); // Setting iterator to work until value exist there while(iter.hasNext()) { // Here we can perform different actions on window' // here in code we are just moving to the windows // and closing all windows opened by webdriver driver.switchTo().window((String) iter.next()).close(); }
Taking snapshot in Webdriver
// Creating webdriver object FirefoxDriver driver = new FirefoxDriver(); driver.get("http://rediff.com"); // Taking screenshot in Webdriver File outSnapshot = driver.getScreenshotAs(OutputType.FILE); // Use FileUtils class to copy snapshot taken in //previous step to my disk FileUtils.copyFile(outSnapshot, new File("C:\\snaps.png")); Difference between Assert and Verify
Verify: If verify got failed, it will fail that particular step and execution will move to next step, remaining steps will execute of that test case
Assert : If assert got failed, execution of that test case will halt on that step, no more steps of that test case will execute
How to implement object repository in Selenium OR How to manage elements in Selenium?
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
In selenium, first we pick element locator of all elements on which we are supposed to perform our action and place in a property file(Here property file behave as Object Repository for Selenium) Now wherever in our test case, element locator value is required. We fetch element locator value from properties file (this is called properties file because extension of this file is .properties) To fetch value of element locator from property file, we need to create object of “ResourceBundle” class and by that object we can use getString method. What are Desired Capabilities? Desired Capabilities help to set properties for the Web Driver. A typical use case would be to set the path for the Firefox Driver if your local installation doesn't correspond to the default settings. DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setCapability(CapabilityType.PROXY, proxy); How to perform Keyboard and Mouse Operations in Selenium Or How to Handle Page onLoad Authentication
For attachment and downloading we need to perform some keyboard or mouse operations, for that we have few options in Selenium 1. Through ROBOT Class of JAVA To perform keyboard operation To perform mouse operation Robot action = new Robot(); action.keyPress(KeyEvent.VK_0); action.keyRelease(KeyEvent.VK_0); action.mousePress(MouseEvent.MOUSE_CLICKED); action.mouseMove(10, 20);
3 AutoIT (Page Onload authentication and Keyboard and Mouse Operations) Sometimes when you are Automating Web pages, you may come across Page onload Authentication window. This window is not java popup/div. It is windows popup. Selenium directly cannot handle this windows popup. This tool can also be used to handle windows that’s comes while attaching and downloading attachment with email.
2 Through Actions class of Selenium Webdriver To perform keyboard operation To perform mouse operation Perform Right Click Perform double click Drag and Drop Scroll Up and down the window Actions action = new Actions(driver); action.click(); action.doubleClick(); action.dragAndDrop(By.id("sourceelementlocator"), By.id("destinationelementlocator")); action.contextClick(); // Right Click action.keyDown(Keys.CONTROL); // Move cursor to the Other Element WebElement mnEle = dr.findElement(By.id("shop")); action.moveToElement(mnEle).perform();
What is POM in Selenium ? What is its advantage ?
POM refers to Page Object Model which encapsulate the internal state of a page into a single page object. UI changes only affect to a single Page Object, not to the actual test codes. Advantages : Code re-use: Able to use the same page object in a variety of tests cases. www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Reduces the amount of duplicated code. How can we get the font size, font color, font type used for a particular text on a webpage using Selenium web driver? driver.findelement(By.Xpath("Xpath ").getcssvalue("font-size” or “font-colour” or “font-type”); How to overcome same origin policy through web driver? DesiredCapabilities capability=new DesiredCapabilities(); capability.setCapability(CapabilityType.PROXY,"http://wpadnod.microsft.com/wpad.dat"); FirefoxDriver f = new FirefoxDriver(capability); How to Get page title in selenium webdriver ? driver.getTitle(); How to Get Current Page URL In Selenium WebDriver driver.getCurrentUrl(); Check Whether Element is Enabled Or Disabled In Selenium Web driver. boolean fname = driver.findElement(By.xpath("//input[@name='fname']")).isEnabled(); System.out.print(fname); Above syntax will verify that element (text box) fname is enabled or not. You can use it for any input element. Does WebDriver support file uploads? Yes, You can't interact with the native OS file browser dialog directly, but we do some magic so that if you call WebElement#sendKeys("/path/to/file") on a file upload element, it does the right thing. Make sure you don't WebElement#click() the file upload element, or the browser will probably hang. Difference between Absolute path & Relative path. Absolute path will start with root path (/) and Relative path will from current path (//) How do you verify if the checkbox/radio is checked or not ? driver.findElement(By.xpath("xpath of the checkbox/radio button")).isSelected(); How do you handle alert pop-up ? To handle alert pop-ups, we need to 1st switch control to alert pop-ups then click on ok or cancle then move control back to main page. SyntaxString mainPage = driver.getWindowHandle(); Alert alt = driver.switchTo().alert(); // to move control to alert popup alt.accept(); // to click on ok. alt.dismiss(); // to click on cancel. //Then move the control back to main web pagedriver.switchTo().window(mainPage); → to switch back to main page. How to get typed text from a textbox ? String typedText = driver.findElement(By.xpath("xpath of box")).getAttribute("value")); www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
What is WebDriverBackedSelenium ? WebDriverBackedSelenium is a kind of class name where we can create an object for it as below: Selenium wbdriver= new WebDriverBackedSelenium(WebDriver object name, "URL ") The main use of this is when we want to write code using both WebDriver and Selenium RC, we must use above created object to use selenium commands. How to get the number of frames on a page ? List <WebElement> framesList = driver.findElements(By.xpath("//iframe")); int numOfFrames = frameList.size();
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
www.thetestingworld.com
Call/Whatsapp - 874391 3121
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Why JAVA code is machine and platform independent?
When we compile java code, it convert java file to byte code (class file) rather than machine code, byte code is machine and platform independent (.class file). We can interpret these class file to any machine having JVM, JVM is used to interpret class file and convert it to machine dependent code and then execute it. What are different types of access modifiers?Access modifiers are used while creating class, method or variable. public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can be accessed inside class only can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. Default : Can be accessed only to classes in the same package. What is Garbage Collection and how to call it explicitly?When an object is no longer referred to by any variable, java/JVM automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
What do you understand by keywords String , StringBuffer and StringBuilder ?
Strings can be handled by 3 classes in Java: String, StringBuffer, StringBuilder
String String Class is immutable object cannot be modified (all changes that we are doing(uppercase, lowercase, substring etc) on string object, is creating a new string object and old data still persist and become garbage(lot of garbage is generating, impact on performance)
StringBuffer StringBuffer is mutable
StringBuilder StringBuilder is mutable
objects can be modified
objects can be modified
StringBuffer is thread safe(synchronized) but slow
StringBuilder is not thread safe(not synchronized) and fast
This keyword in java This keyword can be used with variable, with the help of this keyword we can set which one is class variable and which one is local variable(this.variable name shows , this is a class variable) This keyword can also be used to call current class overloaded constructor. This keyword can be used to call current class methods
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Static keyword in Java
Static keyword in Java can be used with variable, method and nested class(class inside another class) static variable: static variable holds single memory location independent to number of objects we have created, all objects will access data from same memory location. static methods: static methods are like static variable holds single memory location for all objects. STATIC methods/variable can be called by the class name itself without creating object of the class Static nested class object created without creating object of its outer class Methods, variables which are not static is called instance variable/methods Super keyword in Java Super keyword in java is used to call parent class override method or parent class constructor Super Class Method Calling 1--> In case child class override, parent class method. When we create child class object and call override method it will access child class method but if we want to access parent class method, we are going to use super keyword Super Class Constructor Calling 2--> super keyword is used to call parent class constructor as well Difference between :` Abstract Method Methods which are just declared not defined or method without body.
Abstract Class
Concrete Method Methods which are declared and defined as well or method with body.
Concrete Class
Class with abstract & concrete methods. Having at least 1 abstract method
Class with concrete methods only
Cannot create object of abstract class
Can create object of concrete class
Abstract Class
Interface
Class with Abstract + Concrete methods
Interface can have only abstract methods
Can have constants as well as variable
Variable declared are by default final(means constants)
We can inherit only 1 class
We can inherit multiple interface(by this way java is supporting multiple inheritance)
Use extends keyword for inheritance
Use implements keyword for inheritance
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
JAVA OOPS Concepts
Polymorphism: means same name multiple use. Overloading and Overriding concept in java implements polymorphism 2 type polymorphism: Compile Time and RunTime Overriding is a runtime polymorphism as 2 methods are having same name and signature so at the run time it is decided which method to call Overloading is a compile time polymorphism, as while compiling JVM knows which method is to call by number and type of arguments Inheritance: With the help of inheritance, we can transfer the properties of a class to child class Data Encapsulation: Wrapping up of data and function in a single unit is called encapsulation. In java class implements the concept of encapsulation Data Abstraction: Make class/ methods abstract Abstract class and Interface implements the concept of Data Abstraction
What is method overloading and method overriding?Method Overloading: When more than 1 method in a class having the same method name but different signature (Different signature means different number and type of arguments) is said to be method overloading. Method Overriding: When patent and child class have same name and same signature (signature means number and type of arguments) method, this is called method overriding. (Method overriding exist in case of inheritance only, when we are making parent-child relationship between classes)
Inheritance With the help of inheritance we can transfer the properties of a class to another class Class which is inherited is called Parent Class or Super Class Class which inherit other class is called Child Class or Sub Class After inheritance, child class objects can access parent class method and variables . extends is the keyword which is used to inherit class implements is the keyword which is used to inherit interface Type of Inheritance Single/Simple Inheritance Supported in Java
Multilevel Inheritance
Supported in Java
www.thetestingworld.com
Multiple Inheritance
Hybrid Inheritance
Not directly supported (supported through interface)
Not directly supported (supported through interface)
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Constructors Constructor can be defined as a group of code (same like method) which is used for initialization Initialization means anything that we want to perform at start Points to remember: Constructor name is always same as class name Constructor does not return any value so we don’t write void while creating constructor Constructors are automatically called when object is created we need not to call them explicitly as we do in methods( as constructor is automatically called when object is created so all code pasted inside constructed is executed before we use class object to call any other methods, that’s why it is called initialization)
We can have more than 1 constructor in a class with different signature, this is called constructor overloading Exception handling in Java 1>> throws keyword : we can place throws keyword in front of our method definition and we can mention classes of all exception which we want to handle or we can mention parent class Exception 2>> Try –catch -- finally block Code that can throw exception, need to be placed in try block After getting exception, whenever the action we want to perform will be placed in catch block If we want to perform some task at the end does not matter exception came or not we will paste that code in finally block We can use try block then catch block try block then finally block(we can skip catch block) try block then catch block then finally block Difference between Throw and Throws in Exception handling 1--> Throws is used in Method Signature while Throw is used in Java Code (send the instance of Exception class) 2--> Throws, we can mention multiple type of exception, separated by comma while in throw we can set only 1 exception class instance 3-->Throws keyword just throws exception need not to handle it, throw pass exception instance to caller program
What do you understand by keywords final, finalize and finally?-
final : final keyword can be used for class, method and variables. A final class cannot be inherited, a final method can’t be override. A final variable becomes constant, we can’t change its value finally : finally, keyword used in exception handling. It is used with a block of code that will be executed after a try/catch block has completed The finally block will execute whether or not an exception is thrown. Means if exception is not throws then Try execute then Finally will execute, in case when exception is thrown finally will execute after catch e Example : Like we have written DB connection code in try block but exception comes In that case connection persist with DB and no other user are allowed to create connection, So in that kind of scenario we want whatever the condition comes, may be exception or not, my DB connection should break, for that I’ll paste connection breaking code in finally() block
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
finalize() : finalize() method is used to code something that we want to execute just before garbage collection is performed by JVM Generic Method/ Classes in Java
In java Generic can be used with Methods and Classes Generic means we create generic method which serves our multiple purposes like we can use same method for multiple tasks like, sorting an integer array, String array etc. Generic Methods : We can create generic methods which can be called by different type of arguments, methods will server request on the behalf of type of argument coming with request
Collection in Java OR List in Java OR Set in Java or MAP in Java
Collection is a interface, which gives architecture to hold multiple data by same name In JAVA, Collection interface is implemented by Set, List and Map
SET
LIST
MAP
-It is used to hold multiple data (same or different data type)
-It is used to hold multiple data (same or different data type)
-Cannot hold duplicate values
- Can hold duplicate values
-Can have maximum 1 null value
-Values can be accessed by index same like Array
Map holds data in the form of key value pair
Difference between Array and ArrayList
Array
ArrayList
Use to hold multiple data of single data type
Use to hold multiple data of single/diff data type
Need to define size of array
Need not to define size, size automatically increase /decrease as we add/remove element
Can access data through index
Can access data through Iterator
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
How to Iterate on HashMap?
Answer: Iterating to List and Set is very simple but in case of HashMap we have to use an extra method "keySet" which pass hashmap object to Iterator package mypack; import java.util.HashMap; import java.util.Iterator; import org.junit.Test; import org.openqa.selenium.ie.InternetExplorerDriver; public class MyClas { public static void main(String aa[]){ HashMap hp = new HashMap(); hp.put("K1", "Val1"); hp.put("K2", "Val2"); Iterator itr= hp.keySet().iterator(); while(itr.hasNext()){ String k = itr.next().toString(); System.out.println(hp.get(k)); }}}
www.thetestingworld.com
TESTING WORLD
www.thetestingworld.com
Call/Whatsapp - 874391 3121
Java Programs for Selenium Interview Interchanging Values of 2 variable without using 3rd Variable package org.abc; public class Tst1 { public static void main(String aa[]) { int i,j; i=100; j=300; i=i+j ; // 400 j=ij;// 400300 =100 Now j=100 i=ij; //400100 =300 Now i=300 // Here we can see values exchanged successfully without using 3rd variable System.out.println(i); System.out.println(j); } } Printing * Triangle * ** *** package mypack; public class MyClas { public static void main(String aa[]) { int Num=3; int i,j,k; System.out.println("Star Triangle up to "+Num+" line is below" ); // Here First loop is created for switching line for(i=0;ii;j) { System.out.print(" "); } // Here this loop is created for printing * in every line for(k=0;k
View more...
Comments