Crack Selenium Interview 1 by 1
Crack Selenium Interview 1 by 1
Locators:
Id, Name, Tag name, Class Name, linkText, Partial Link Text, CssSelector, Xpath
Syntax for finding element: [Also learn the syntax for each locator]
Driver.findElement(By.Locator(“locator Value”));
Example: Driver.findElement(By.Id(“idvalue”));
***********************************************************************************
Note: For browsers other than Firefox we have to set the browser driver (exe) file and declare where it is placed
before instantiating the browsers.
System.setProperty(“Webdriver.chrome.driver”, “D://Foldername//chromedriver.exe”);
For IE:
System.setProperty(“Webdriver.iedriver.driver”, “D://Foldername//iedriver.exe”);
***********************************************************************************
driver.manage().window().maximize();
***********************************************************************************
Implicit wait:
Selenium will check for the element and wait for the particular time before throwing an exception. This applies
to every element (every line of code) throughout the entire script.
Driver.manage().timeouts().implicitlywait(10, timeUNIT.SECONDS);
Explicit Wait:
Sometimes we cannot judge the time taken for a button to get enabled for clicking. In such cases we can
explicitly ask selenium to wait for a particular condition.
/html/tbody/table/td/tr
Interview Question: (Also you can add it as the challenge faced in automation)
Example:
//input[contains(@src , ’submit’ )+
//input[ends-with(@src , ’submit.gif’ )+
//input[starts-with(@alt , ’submit’ )+
Interview Question: (In a web table (dynamic) find the particular word in a row and print its column values)
http://www.toolsqa.com/selenium-webdriver/handling-tables-selenium-webdriver/
***********************************************************************************Read and
Write Excel : Apache POI
Interview Question:
1. How will you handle Excel?: Ans: two jars available: JXL and Apache POI. Mention the advantage of
Apache POI over JXL. Also make sure to know the latest version of Apache POI.
**********************************************************************************
Get Methods:
getAttribute(); => This will return the value of any attribute in the source code of that element.
Example:
**********************************************************************************
Handling Alert:(Alerts can not be inspected: If there is no Alert in the screen you will get
“NoAlertPresentException”)
Alert a = driver.switchto().alert();
Handling Frames: (If tag name starts with “Frame” or “Iframe” then it is a frame)
Syntax: driver.switchto().frame();
Once you are done with the frame: you have to move out of frame:
driver.switchTo().defaultContent();
*********************************************************************************
Driver.switchTo().window(winHandle);
Interview Question:
Suppose your test script opens 3 new tabs/windows: Selenium webdriver assigns unique handle to each window.
But it can get the Window Handle of the parent window alone using the “ getWindowHandle()” method. To
get the window Handle of other windows we have to use “getWindowHandles()” method which would return a
“Set” of strings. (Set is a collection class in Java and the reason for using “Set” instead of “List” is
window handles are unique values and Set allows only uniqiue entry .)
Then using “for each” loop iteration : we have to iterate through each window handle and complete testing.
Finally if we want to move back to parent window: we can use its windowHandle which we stored initially.
Actions Class:(To perform keyboard and mouse actions. Actions should end with build().perform(); )
(Mouse hover and Drag and Drop methods are enough)
Builder.moveToElement(ele1).build().perform();
***********************************************************************************
1.Select by Value:
S.SelectByValue(“2”); => This will select the drop down option for which value is set as “2” in the
source code
2. Select by index:
S.SelectByindex(5); => This will select the drop down option at the fourth postion. (Indexing starts
with 0 hence 5-1 = 4)
S .SelectByVisibleText(“someText”); =>This will select the drop down option with the text value
“someText”.
Interview Question:
How will you select the last option in the dropdown?
S.getOptions(); => This will return me the total number of options. Then using the select by index we can
select the desired option.
Interview Question:
Without using “select” how will you select drop down value? Ans: Using Actions class we can do that. Identify the
element. Using the click method of Actions class click the dropdown and then click down arrows using the
method sendKeys(keys.Down) and then click the desired element.
********************************************************************************
Grid:
Grid is used to achieve remote execution. One machine will act a Hub (Master) and it will check for the
connected machines called Nodes and based on the Actual capabilities will send the requests to the nodes and
execute on them.
Desired Capabilities: These are the user desired values like run my test script in Chrome and Windows platform.
dc.setBrowserName(“chrome”);
dc.setPlatform(platform.Windows);
Actual Capabilities: If 2 machines (Nodes) are connected to my Hub: the Hub will check for the machine (Node)
with Chrome Browser and Windows platform and send execute the script on that.
(Here 4444 is a default port number and we can give any value:
*********************************************************************************
Framework:
Advantages of Framework:
Types of Framework:
Interview Question:
Components in a framework:
Interview question:
Explain your framework? Ans: Tell everything from the above section.
*************************************************************************************
TestNG:
TestNG is a framework similar to Junit.
Advantages of TestNG:
@Test Attributes:
Invocation Count: To run the script multiple times. (example: @Test (invocation count =2)
Enabled: To run/skip a script. (Example: @Test(enabled = true) ) [By default the enabled will be set as true. If
you set that as false that script will be skipped.]
Priority: To set priority to the execution order of @Test (Scripts) . (example: @Test (Priority =1) [Note: Priority
takes the order of least value to a higher value. If two @Test have priority 2 and 5 respectively: @Test with
priority 2 will be executed first).
Interview Questions:
Parall Execution:
In the above code if we change the first line of code as:
1. Screenshots taken in browsers other than “Firefox” will not cover the entire webpage. Only the area with
the element of focus will be covered. Solution: Use Actions class to move (scroll) the webpage up/down
and take screenshots.
2. Dynamically changing xpath: Solution: Used partial xpath to handle it.
3. Need to start scripting before the application is ready. That is we have mockup screen alone. Solution:
Using Properties file concept and handled it. Once the application is ready we will simply change the
code in the properties file rather than changing script.
4. Need to upload a document from my computer as part of sanity testing which would need windows
application interactions. We can achieve it using tools like Sikuli or Autoit. But in client machines we
should not install such tools. Solution: There is a method “Robot.awt” under “Java.AWT” package.
*Concept: store the file path using the “setContents” method to store in clipboard. Then using sendKeys
method send “Ctrl+V” and “Enter.”
5. Reading contents from a PDF file. Solution: Two jar files – “PDF Box” to read PDF and “Font box”
to read/analyze” the contents in the PDF. (Limitation: It cannot read images/tables. Only text will be
read.)
6. Run execution in the background or Hidden mode. Solution: HTML Unit driver is used to run scripts in
the background. That is we don’t want any browser to run in the foreground.
[Limitation of HTML unit driver: it cannot take screenshot. Mouse hover, Key board actions cannot
be performed].
*****************************************************************************
JAVA Topics
Basic OOPS:
1.Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
class Employee{
int salary=40000;
} Output:
class Programmer extends Employee{ Programmer salary is:40000
int bonus=10000;
Bonus of programmer is:10000
public static void main(String args[]){
2.Polymorphism:
2.a.Method Overloading:
If a class have multiple methods by same name but different parameters (or argumenents),
it is known as Method Overloading. Also we can say as when the method arguments are
either different by type or count.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);} output: 30 40 16
void sum(float d, float e){System.out.println(d+e);}
If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding.
3.Constructor:
- Constructor is like a method.
- Name of the constructor should be the name of the class.
- no return type.
- constructor will be called whenever you create an instance of the class.
-Types: a.Default Constructor b.Parameterized Constructor
3.a.Default Constructor:
Constructor without parameter. Used to give default value to the object.
Out put:
Class Bike { Bike is created
Bike (){
System.out.println(“Bike is created”);
}
Public static void main (String[] args) {
Bike B = new Bike();
}}
–A method that is declared as abstract and does not have implementation is known
as abstract method.
•A generic operation
•Part of an abstract class
–Must be implemented by a concrete subclass
•Each concrete subclass can implement the
method differently
•Real usage:
- If you cannot define concrete implementation of method in superclass; then you can
define it as abstract method. So that you force the subclass developer to implement the
logic.
- e.g., break this can vary between types of car.. [sports car VS normal car]; just define the
break as abstract method in super class; so the sub class developers implement the behavior.
- All the methods in sub class should definitely be implementing the behavior else the class
becomes abstract again.
Drawing circle
class TestAbstraction{
public static void main(String args[]){
Drawing rectangle
Shape s1=new Circle();
//In real scenario, object is provided through method e.g. getShape() method
//Note: you can also use Circle s1 = new Circle(); instead of Shape S1 = new Circle();
Shape S2=new Rectangle();
S1.draw();
S2.draw();
}
}
6.Interface:
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In
the sense, when a class extends an abstract class, it can’t extend any other class. So we
go for Interfaces.
Interface is:
Abstract classes which are completely unimplemented.
- Every method is abstract.
- A class implement any number of interfaces.
•All the methods in interface should be implemented in subclass else it becomes abstract class.
•Cannot be instantiated
Example code:
interface Steerable {
public void turnLeft(int deg);
public void turnRight(int deg);
interface Mode{
public void frontWheel();
public void backWheel();
}
}
Java Keywords
Static:
- Can be applied to variable / method / inner-class / blocks
- Memory efficient [Saves memory] e.g., common property for all objects [company name
of employees]
- Java static property is shared to all objects. One time declaration is enough.
Example of static variable:
Class Student{
int rollno;
String name;
static String college ="ITS"; //String variable college is declared as static
s1.details();
s2.details();
}
}
}
Example of static method:
//Program of changing the common property of all
objects. s1.details();
class Student{ s2.details();
int rollno; }
}
String name;
static String college ="ITS"; //String variable college is
declared as static
Class testFinal{
final int a =5;
public static void main (string[] args){
System.out.println(a);
//If you give System.out.println(a++); - you will get compilation error as the value
of a is 5 and cannot be changed since its declared as final.
Super:
The super keyword in java is a reference variable that is used to refer immediate parent
class object.
Usage of java super Keyword
1.super is used to refer immediate parent class instance variable.
2.super() is used to invoke immediate parent class constructor.
3.super is used to invoke immediate parent class method.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
Output:
class Bike extends Vehicle{
Bike(){
super();//will invoke parent class constructor Vehicle is created
System.out.println("Bike is created"); Bike is created
}
public static void main(String args[]){
Bike b=new Bike();
}
}
class vehicle {
void run(){
System.out.println("vehicle is created");
}
}
class car extends vehicle {
void run(){
System.out.println("car is created");
}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method }
2.Array list:
- Variable length collection class.
- To get the size use “size()” method.
3.Hash Map:
- A HashMap contains values based on the key. It implements the Map interface and
extends AbstractMap class.
- It contains only unique elements.
- It may have one null key and multiple null values.
- It maintains no order.
class Hashmap{
public static void main(String args[]){
HashMap<Integer,String> hm=new
HashMap<Integer,String>();
OUTPUT:
hm.put(100.”Amit”);
102 Rahul
hm.put(102,"Vijay");
100 Amit
hm.put(103,"Rahul");
101 Vijay
for(Map.Entry m:hm.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue()); } } }
- 4. HashTable
-
- A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is
identified by calling the hashcode() method.A Hashtable contains values based on the
key. It implements the Map interface and extends Dictionary class.
- It is synchronized.
Note:
Also learn List and Set collection class.
Set will be used while handling windows (storing the window handles –
driver.getWindowHandles() method).
List will be used while getting a collection of webelements. findElements(by) method.
**********************************************************************************
Frequently Asked Java Programs
1. Factorial of a Number:
public class Factorial {
public static void main(String[] args) {
int num=5, fact=1;
for(int i=1; i<=num; i++)
{ fact=fact*i; }
System.out.println("The Factorial of the number "+num +" is :" +fact);
}}
6. Palindrome Number:
public class Palindromenumber {
public static void main(String[] args)
{
int rem,sum=0,temp;
int num=252;//It is the number variable to be checked for palindrome
temp=num;
while(num>0){
rem=num%10; //getting remainder
sum=(sum*10)+rem;
num=num/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
7. Palindrome String:
if (rev.equalsIgnoreCase(text))
System.out.println("Validated with String Buffer Method: The given string is palindrome");
else
System.out.println("Validated with String Buffer Method:The given string is not palindrome");
/**********************************************************/
/**************Without Using String buffer methods*************/
String reverse="";
for(int i=text.length()-1; i>=0; i--){
reverse = reverse+text.charAt(i);
}
if (rev.equalsIgnoreCase(text))
System.out.println("Validated without String Buffer Method: The given string is palindrome");
else
System.out.println("Validated without String Buffer Method:The given string is not palindrome");
}
}
8. Prime Number:
public class PrimeNumber {
public static void main(String[] args) {
int num =21, i, flag=0;
//Prime number is one that is not divisible by the numbers starting from "2" to half of that
number //example: For 10: it is prime if it is not divisible by the numbers: 2,3,4,5 where 5 is half of
10
if(num%i==0){
System.out.println("The given number is not prime");
flag=1;
break;
}
}
if(flag==0)
System.out.println("The given number is prime");
}
}