Saturday, June 1, 2019

Some Important Selenium Q&A

1. Why do we actually need a Selenium framework?
2. What are the advantages of using a framework?
3. Characteristics of a framework.
4. How should you define a framework?
Question : Where the results stored in a grid environment?
On execution machine
Question : Suppose I have to extract text using coordinates from a pdf file using java.This is required because
i need to find text from a specific line from a pdf file.
Covert pdf to HTML and find it using Selenium or
Use pdfbox jar, this will extract data from pdf
Question :
When do we use HTTP client to automate REST calls?
and when to use Rest Assured? What is the difference.
Are these two different ways to automate Rest API?
Answer :  HTTP client is a jar file which is taking care of sending and getting the request response to ur server,
HTTP client is more open and gives u freedom programming wise wheras REST ASSURED is a jar file which is like
BDD framework for rest api and u have defined methods flexibilty is bit low and REST assured in turn uses HTTP CLIENT only to test rest.
Question : How to check that all clickable links on the page are removed?
Use tagname locator with String "a"-> which used for links and store it as
List links= driver.findElements(By.tagname("a"));
then use for loop to get links.
for(int I=0;I<=links.size();I++)
{
Syso(links.getText(I));
Or
Syso(links.getFirst(I));
Or
Syso (links.getLast(I));
}
save every href link in list using find elements, then check using is displayed or is enable.


Where we use runtime polymorphism Method overriding in selenium webdriver?
When we use WebDriver driver = new FirefoxDriver(); this is runtime polymorphism

Data-Driven Automation Framework
In this approach, each test case is viewed as a function call to which data is fed from an external source. In the data-driven automation framework, test data is stored in a separate external file thus eliminating the hard coding of test data into test scripts. Thus, it is possible to run the same test case with different sets of test data.
Advantages
Test data is separately maintained thus making it easier to make changes to the test script.Better test coverage possible by using different test data for the same test case.
Disadvantages
It is not possible to test all the real-time business functionalities of the system under test.There is no easy way to specify which data file must be associated with which test script.It needs the tester to have some basic programming skills in the tool that has been chosen to automate the testing.
Java interview programs
Write a Java program to  get the max number from an array?
int[] array = {10,20,15,50} ;
int big= array[0] ;
for(int i=0;i

{
If(array[i]>big)
big=array[i]
}
Sop(big) ;
// without using any sorting method.
What will be the output of the below given program?
public class Test
{
static { i=5; }
static int i;
public static void main(String[] args)
{
System.out.println("i value is "+i);
}
}
Options:
a) 0
b) 5
c) Compilation error
d) 1
Can we have static method in interface?
All methods in an interface are implicitly 'public', 'abstract' but never 'static'.
Can an interface have variables? Can these variables be transient?
All variables in an interface are implicitly static , public and final. They cannot be transient or volatile. A class can shadow the interface variable with its variable while implementing.
What is the use of transient variable? Can a transient variable be static?
Transient variables are not stored as object's persistence state and is not serialized for security. Transient variables may not be final or static. Compilers do not give any errors as static variables and anyways they are not serialized.
Does the 'finalize' method in subclass invoke 'finalize' method in super class?
'Finalize' is not implicitly chained. A 'finalize' method in sub-class should call 'finalize' in super class explicitly as its last action for proper functioning. Compilers does not enforce this check
What is the use of volatile variable?
Volatile can be applied only to variables, not for 'static' or 'final'. Declaring a variable volatile indicates that it might be modified asynchronously, so that thread will get correct value and used in multi-processor environment.
Can an interface be final?
Interface cannot be declared 'final' as they are implicitly 'abstract'.
Map implements collection. True or false?
False, as map does not implement collection.
Can a class implement two interfaces which has got methods with same name and signatures?
Yes, a class can implement two interfaces which has got methods with same name and signatures.
Which one will throw an arithmetic exception: a. int i = 100/0; b. float f = 100.00/0.0
b. [float f = 100.00/0.0. Float division by zero returns NAN (not a number) instead of exception.]
Dictionary is an interface or class?
Dictionary is a class and not an interface.
What is the rule regarding overriding methods throwing exceptions?
Overriding methods cannot throw more generic exception than base method.
A class without a method can be run by JVM if its ancestor class has 'main'. True or false?
Exception in 'finalize' method doesn't prevent GC.
An object is resurrected by making other object refer to the dying object in finalize method. Will this object be ever garbage collected?
Resurrection can happen in 'finalize' method which will prevent GC to reclaim the object memory. However this could be done only once. Next time GC will not invoke 'finalize' method before garbage collection.
Can a class implement two interfaces with same variable names?
If both the interface have same variable and the variable is not declared in implementing class, the compiler will throw an ambiguous error.
Random access file extends from File. True/False?
False [ Random access file descends from object and implements data input and data output.]
public static final main(String[] args) { }is a valid method or not?
Yes it is a valid method.
public main(int number) { } is a valid method or not?
No it is not a valid method.
Java supports both multi-dimensional and nested arrays. True/False?
False [Java does not support multi-dimensional arrays. It only supports nested arrays.]


If you use @Listener annotations and create a Sample Listener for taking screenshot, there we do Method Overriding
what is static method ?can we access static method  using object?
Static methods are unchangeable/still method defined in a class and even main () method is declared as static..so they belong to class level and does not require object to call the method..
classname.methodname is enough to call  static method
Static method are defined in class template as a member of class.when we create a object of the class, it will create a single copy of instance variables and methods ..plus this static method..same for 2nd object creation of class with different values but same static method .
static method don’t need object to be created to call them but directly call with class.
With using class name is enough.No object needed.
Question  : How to create a stub ?
This newly created stub should behave like external system and from when we send request from internal system it should give below response

Response: when I will send a json payload it should give 201 status code and when I will send incorrect json payload it should throw 400 bad request status.

Can you suggest me the approach to develop the stub?
Question : I'm using RestAssured to try and make some API tests like the following
private String BaseURL = "https://api.asos.com/product/search/V1/";
private final String Accept = "application/json";
private final String Store = "1";
private final String Lang = "en";
private final String Currency = "GBP";
private final String OffSet = "0";
private final String Q = "red";
private final String Limit = "10";
@Test
public void redItemRequest(){
given().queryParams("Q",Store,Lang,Currency,OffSet,Limit).
when().get(BaseURL).
then().
assertThat().statusLine(equalTo("HTTP/1.1 200 OK"));
on debug, the request is only using the BaseUrl  string to make the request and it does not use the parameters that I specify.
Can you point out what I might be missing or doing incorrectly and how to correct it so that the request is sent correctly?
Introduction to Java Number
In Java language, we mostly work with a primitive data type, but Java also provides a wrapper class under the abstract class numbers in java.lang package, there are six subclasses under the class ‘numbers’.
The primitive data types are ‘wrapped’ under these Java classes for their corresponding objects. This wrapping is usually done by the compiler. When an object is converted into primitive type than it is called Autoboxing, and when again transferred to an object it is called Unboxing.
Example of Java Number
public class Test
{
public static void main(String args[]) {
Integer x = 5;
// boxes int to an Integer object
x = x + 10;
// unboxes the Integer to a int
System.out.println(x);
}
}
Number Methods in Java
Java xxx xxxValue()
xxx Java Number method, represents the primitive datatypes byte, short, int, long, float, double. This datatype here is used to convert the Java number types into the mentioned types.
Syntax
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
//Java program to demonstrate xxxValue() method
public class Test{
public static void main(String[] args)
{
// Creating a Double Class object with value "6.9685"
Double d = new Double("6.9685");
// Converting this Double(Number) object to different primitive data types
byte b = d.byteValue();
short s = d.shortValue();
int i = d.intValue();
long l = d.longValue();
float f = d.floatValue();
double d1 = d.doubleValue();
System.out.println("value of d after converting it to byte : " + b);
System.out.println("value of d after converting it to short : " + s);
System.out.println("value of d after converting it to int : " + i);
System.out.println("value of d after converting it to long : " + l);
System.out.println("value of d after converting it to float : " + f);
System.out.println("value of d after converting it to double : " + d1);
}
}
Java int compareTo(NumberSubClass referenceName)
This method is used to compare the specified argument and the number object, but two different types cannot be compared, so both the argument and the number should be of the same type.
The Reference could of the type byte, double, float, long, or short.
Syntax
public int compareTo( NumberSubClass referenceName )
//Java program to demonstrate compareTo() method
public class Test{
public static void main(String[] args)
{
// creating an Integer Class object with value "10"
Integer i = new Integer("10");
// comparing value of i
System.out.println(i.compareTo(8));
System.out.println(i.compareTo(10));
System.out.println(i.compareTo(11));
}
}
Java boolean equals(Object obj)
This Java Number method is used to determine whether the number object is equal to the argument.
Syntax
public boolean equals(Object obj)
//Java program to demonstrate equals() method
public class Test{
public static void main(String[] args) {
// creating a Short Class object with value "15"
Short s = new Short("15");
// creating a Short Class object with value "10"
Short x = 10;
// creating an Integer Class object with value "15"
Integer y = 15;
// creating another Short Class object with value "15"
Short z = 15;
//comparing s with other objects
System.out.println(s.equals(x));
System.out.println(s.equals(y));
System.out.println(s.equals(z));
}
}
Constructor
• An object is a section of memory (with
variables and methods), and a class is a
description of objects.
• The new operator calls a class’ constructor
method.
• A constructor has the same name as the class.
• new creates a new object of type String. It is followed by
the name of a constructor. The constructor String() is part
of the definition for the class String.
• Constructors often are used with values (called parameters)
that are to be stored in the data part of the object that is
created. In the above program, the characters Random
Jottings are stored in the data section of the new object.
• Constructors do not return anything.
str1 = new String("Random Jottings");

Java program to convert Fahrenheit scale to Celsius
import java.util.*;
class FahrenheitCelsius {
public static void main(String[] args) {
float temp;
Scanner inn = new Scanner(System.in);
System.out.print(“Enter temperatue in Fahrenheit=”);
temp= inn.nextInt();
temp = ((temp – 32)*5)/9;
System.out.println(“Temperatue in Celsius = ” + temp);
}
}

we can switch over the elements in frames using 3 ways.
By Index
By Name or Id
By Web Element
It is impossible to click iframe directly through XPath since it is an iframe. First we have to switch to the frame and then we can click using xpath.
public class SwitchToframe   {
public static void main(String[] args) throws NoSuchElementException{
WebDriver driver = new FirefoxDriver();
driver.get("http://XYZABC.com/test/xxxhome/");
driver.manage().window().maximize();
//int size = driver.findElements(By.tagName("iframe")).size();
/*for(int i=0; i<=size; i++){
driver.switchTo().frame(i);
int total=driver.findElements(By.xpath("html/body/a/img")).size();
System.out.println(total);
driver.switchTo().defaultContent(); //switching back from the iframe
}*/
//Commented the code for finding the index of the element
driver.switchTo().frame(0); //Switching to the frame
System.out.println("***We are switched to the iframe**");
driver.findElement(By.xpath("html/body/a/img")).click();
//Clicking the element in line with Advertisement
System.out.println("****We are done******");
}
}
Question: Can we override static method?
Answer:We cannot override static methods. Static methods are belogs to class, not belongs to object. Inheritance will not be applicable for class members
Question: What is the difference between super() and this()?
Answer:super() is used to call super class constructor, whereas this() used to call constructors in the same class, means to call parameterized constructors.

What is Selenium Grid?
Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems.
In simple words, it is used to distribute our test execution on multiple platforms and environments concurrently.
When do we use Selenium Grid?
Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution
What are the advantages of Selenium Grid?
It allows running test cases in parallel thereby saving test execution time.
It allows multi-browser testing
It allows us to execute test cases on multi-platform
What is a Framework?
A framework defines a set of rules or best practices which we can follow in a systematic way to achieve the desired results. There are different types of automation frameworks and the most common ones are:
Data Driven Testing Framework
Keyword Driven Testing Framework
Hybrid Testing Framework
How many test cases you have automated per day?
It depends on Test case scenario complexity and length. I did automate 2-5 test scenarios per day when the complexity is limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.

WindowsUtils class in Selenium Webdriver

WindowsUtils class provides methods to handle the process on the command prompt, with the methods present in the WindowsUtils class we can get path details and kill process.
WindowsUtils methods will kill only the things present on the local machine,
WindowsUtils class doesnot have any effect on the remote machines
WindowsUtils class is present under org.openqa.selenium.os package, all the methods present under this package are static methods.
Methods present in WindowsUtils Class
1. findSystemRoot()
2. findTaskKill()
3. getEnvVarIgnoreCase(java.lang.String var)
4. getPathsInProgramFiles(java.lang.String childPath)
5. getProgramFiles86Path()
6. getProgramFilesPath()
7. killByName(java.lang.String name)
8. killPID(java.lang.String processID)
9. loadEnvironment()
10. thisIsWindows()

Data-Driven Automation Framework
In this approach, each test case is viewed as a function call to which data is fed from an external source. In the data-driven automation framework, test data is stored in a separate external file thus eliminating the hard coding of test data into test scripts. Thus, it is possible to run the same test case with different sets of test data.
Advantages
Test data is separately maintained thus making it easier to make changes to the test script.Better test coverage possible by using different test data for the same test case.
Disadvantages
It is not possible to test all the real-time business functionalities of the system under test.There is no easy way to specify which data file must be associated with which test script.It needs the tester to have some basic programming skills in the tool that has been chosen to automate the testing.

polymorphism is the ability by which, we can create functions or reference variables which behaves differently in different programmatic context.
There are two types of Polymorphism
Compile time polymorphism (static binding or method overloading)
Runtime polymorphism (dynamic binding or method overriding)
Polymorphism is implemented in Java using method overloading and method overriding concepts.

What is an exception?
An exception is thrown whenever an unusual event occurs in Java say for instance there is an incorrect code written it will give an unexpected result. Whenever an exceptional event occurs, it will create a hindrance to the normal flow of the program. Exceptional handler is that snippet of code which helps in catching and resolving the exception.
How are the exceptions handled in Java?
Whenever an exception occurs the process of execution of the program is transferred to an appropriate exception handler. The try-catch-finally block is used to handle the exceptions. The code in which the exception may occur is enclosed in a try block, also called as a guarded region. The catch clause matches a specific exception to a block of code which handles that exception and the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block.
Exceptions are defined in which java package?
All the exceptions are subclasses of java.lang.Exception.

What is Runtime Exception or unchecked exception?
Runtime exception represents the problems that occurs because of a programming problem. Such problems include some of the following: 1. Arithmetic exceptions: eg dividing by zero 2. Pointer exceptions: eg trying to access an object through a null reference 3. Indexing exceptions: eg attempting to access an array element through an index that is too large or too small. Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program and in a typical one there can be numerous. By adding runtime exceptions in every method declaration a program's clarity will get reduced. Thus, the compiler does not require one to catch or specify runtime exceptions (although one can). The solution is to rectify the programming logic wherever the exception has occurred or provide a check.
What is a checked exception?
Checked exceptions forces the programmer to catch them explicitly in try-catch block. It is a subclass of Exception. Example: IOException
What is difference between an error and exception?
An error is an irrecoverable condition occurring at runtime say for instance 'OutOfMemory' error. These JVM errors cannot be repaired at runtime. Though error can be caught in catch block still the execution of application will come to a halt and is not recoverable. On the other hand exceptions are conditions that occur because of bad input or human error. For e.g. 'FileNotFoundException' will be thrown if the specified file does not exist or a 'NullPointerException' will take place if one tries using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)
What is the use of 'throws' keyword?
If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the 'throws' clause at the function declaration.
public void parent()
{
try
{
child();
}
catch(MyCustomException e)
{
}
}
public void child throws MyCustomException
{
//put some logic so that the exception occurs.
}
What is a 'throw' keyword?
'Throw' keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application. The exception thrown should be subclass of 'Throwable'.
public void parent()
{
try
{
child();
}
catch(MyCustomException e)
{
}
}
public void child
{
String iAmMandatory=null;
if(iAmMandatory == null)
{
throw (new MyCustomException("Throwing exception using throw keyword");
}
}
What are the possible combinations to write try, catch and finally block?
1) try
{
//lines of code that may throw an exception
}
catch(Exception e)
{
//lines of code to handle the exception thrown in try block
}
finally
{
//the clean code which is executed always no matter the exception occurs or not.
}
2 )  try{  }  finally{  }
3 )   try{
}
catch(Exception e)
{
//lines of code to handle the exception thrown in try block
}
The try block must be always followed by the try block. If there are more than one catch blocks they all must follow each other without any other block in between. The finally block must follow the catch block if one is present. If the catch block is absent the finally block must follow the try block.
can we create abstract class without abstract method?
Yes.Abstact class may or may not have abstact method but if u declare any method as abstact then class must be abstact.

What is Singleton class in java?
singleton class happens to be a class that when the console executes it, then it will only stay ther unti the entire class sucessfully finishes. Think it like your payment gateway,once you enter there then you can only proceed forward,if anything fails then the entire session fails
Can a catch block throw the exception caught by itself ?
Yes, a catch block can throw the exception caught by itself which is called as rethrowing of the exception by catch block. e.g. the catch block below catches the FileNotFound exception and rethrows it again.
void checkEx() throws FileNotFoundException
{
try
{
//code that may throw the FileNotFoundException
}
catch(FileNotFound eFnf)
{
throw FileNotFound();
}
}

What is an abstract class ?
These classes cannot be instantiated and are either partially implemented or not at all implemented.
This class contains one or more abstract methods which are simply method declarations without a body.

When is an abstract method used ?
An abstract method is declared in the parent class when we want a class which contains a particular method but on the other hand we want its implementation to be determind by child class.

Can an interface be extended by another interface in Java ?
An interface can be extended by another interface in Java.
The code for the same would be like as shown below:
// this interface extends from the Body interface:
public interface FourLegs extends Body
{
public void walkWithFourLegs( );
}

Differentiate an Interface and an Abstract class.
An abstract class may have many instance methods which sport default behavior.
On the other hand, an interface cannot implement any default behaviour.
However, it can declare different constants and instance methods.
Whereas an interface has all the public members, an abstract class contains only class members like private, protected and so on.

What is a marker interface?
Marker interface is an interface with no fields or methods in Java.
Uses of marker interface are as follows:
• We use marker interface to tell java compiler to add special behavior to the class implementing it.
             Java marker interface has no members in it.
•It is implemented by classes in order to get some functionality.
For instance when we want to save the state of an object then we can implement serializable interface.

what is static method ?can we access static method  using object?
Static methods are unchangeable/still method defined in a class and even main () method is declared as static..so they belong to class level and does not require object to call the method.
classname.methodname is enough to call  static method


Bug Life Cycle