SEL QA
SEL QA
SEL QA
What’s
the most interesting bug that you’ve found, and why?
Concise. Your test plan should be no longer than one page with bullet points.
Readable. The document should be easy to read, avoiding technical language where possible.
Flexible. Your test plan should be adaptable and not fixed in stone. You want to create
documentation that won't hold you back if new information comes along or changes need to be
made.
Requirements:
100% Requirements coverage is achieved.
Defects:
Defined / Desired Defect count is reached.
All Show Stopper defects or Blockers are fixed and No known Critical / Severity 1
defect is in Open Status.
All High Priority defects are identified and fixed.
Defect Rate falls below defined acceptable rate.
Very few Medium Priority defects are open and have a workaround in place.
Very few low priority open defects that do not impact software usage.
All High Priority defects are re-tested and closed and corresponding Regression
scenarios are successfully executed.
Test Coverage:
Test Coverage should be 95% achieved.
Test case Pass Rate should be 95%. This can be calculated by formula
( Total No of TCs Passed / Total number of TCs ) * 100.
All critical Test cases are passed.
5% Test cases can be failed but the Failed Test cases are of low priority.
Complete Functional Coverage is achieved.
All major functional / business flows are executed successfully with various inputs
and are working fine.
Deadlines:
Project Deadline or Test Finish deadline is reached.
Test Documents:
All Test Documents / deliverables (Example – Test Summary Report) are prepared,
reviewed and published across.
Budget:
Complete Testing Budget is exhausted.
“Go / No Go” Meetings:
“Go / No Go” meeting has been conducted with stakeholders and a decision is made
whether the project should go to production or not.
Checklist
Are all test cases executed at least once?
Is the Test Case Pass rate as defined?
Is complete test coverage achieved?
Are all functional / Business flows executed at least once?
Is the decided defect count reached?
Are all Major High Priority Defects fixed and closed?
Have all Defects been Retested and closed?
Has Regression been done for all open defects?
Have you exhausted the testing budget?
Has the Testing end time reached?
Are all Test Deliverables reviewed and published?
4. If I left you testing for two hours, what would you have
to show me when I returned?
1. A kick start generic test pan based on previous experience.
2. Set of questionnaire to understand the functionality or application(if new)
By testing the software, finding and tracking the bugs and through suggestions
of improvement ideas, you are contributing towards the betterment of the
product; it surely is the most satisfactory job.
To cover the vast range of devices available and to check the application’s
behavior in terms of response time and usability is a big challenge.
A good software tester is the one, who understands what customer wants, who
studies the market, who understands latest trends, who provide relevant
information to the client, who interprets how important the product is for the customer
and ultimately who can be in customer’s shoes and work on a product.
A negative test case tests that a system does not do things it shouldn't.
Example: should not allow you to login when invalid credentials are supplied.
//alertIsPresent() condition applied
if(w.until(ExpectedConditions.alertIsPresent())==null)
System.out.println("Alert not exists");
else
System.out.println("Alert exists");
All the windows, which will open inside your main window, will be termed as child windows.
Window Handle - A unique identifier holds the address of all the windows. Think of it as a pointer to a
window, which returns the string value. Assume that each browser will have a unique window handle.
This window handle function helps to retrieve the handles of all windows.
Set<String> s=driver.getWindowHandles(); //Get the handles of all the windows that are currently open
using the command
while(win.hasNext())
{String child_window=win.next();
if(!parent.equals(child_window))
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close(); }}
driver.close();
driver.switchTo().window(tabs2.get(0));
5. Disadvantages of Selenium
1. No support for desktop applications – Selenium does not support testing for desktop
applications.
2. Expertise – Selenium requires expertise of your team — and resources to manage.
3. Maintenance and Scalability – Selenium is a maintenance-heavy framework — and is difficult to
scale as one grows.
4. Open Source Forums – Since Selenium is open source software, one has to rely on community
forums to get your technical issues resolved.
5. No support for REST and SOAP Platforms – We can’t perform automation tests on web services
like SOAP or REST using Selenium.
6. No Reporting capability – Selenium does not have any inbuilt reporting capability, one has to
rely on plug-ins like JUnit and TestNG for test reports.
7. Image Testing – It is not possible to perform testing on images. One needs to integrate Selenium
with Sikuli for image testing.
1 It is responsible for loading the page and It is only responsible for redirecting the
waits until the page has finished loading. page and then returning immediately.
2 It cannot track the history of the browser. It tracks the browser history and can
perform back and forth in the browser.
driver.get(url);
driver.manage().timeouts().implicitlyWait(12,
TimeUnit.SECONDS);
navigate()
driver.navigate().to(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
driver.navigate().refresh();// refresh the current browser
driver.findElement(By.cssSelector("input[name=’search’]")).
sendKeys("Selenium");//Using id tagname attribute combination for
css expression
driver.navigate().back();//go back to the previous page
driver.navigate().forward();//browser will go move to the next page
driver.close();
preceding-sibling - //td[contains(text(),'Cow')]/preceding-
sibling::td/input[@type='checkbox']
driver.findElement(By.xpath("//*[@id='vContactsForm']/table/tbody/tr["+i+"]/td[1]/input")).click();
}
}
//Method-2:
driver.findElement(By.xpath("//a[contains(text(),'test2
test2')]/parent::td//preceding-sibling::td//input[@name='contact_id']")).click();
driver.findElement(By.xpath("//a[contains(text(),'ui
uiii')]/parent::td//preceding-sibling::td//input[@name='contact_id']")).click();
1. A Map cannot contain duplicate keys and each key can map to at most one
value. Some implementations allow null key and null values like
the HashMap and LinkedHashMap, but some do not like the TreeMap.
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders,
while HashMap does not.
3. There are two interfaces for implementing Map in java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.
Explain framework (Questions based on your framework
explanation)
12. What is Pom.xml
POM stands for Project Object Model. It is fundamental unit of work in Maven. An XML file resides in
the base directory of the project as pom.xml.
The POM contains information about the project and various configuration detail used by Maven to
build the project(s).
POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in
the current directory. It reads the POM, gets the needed configuration information, and then executes
the goal. Some of the configuration that can be specified in the POM are following −
project dependencies
plugins
goals
build profiles
project version
developers
mailing list
Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its
version as these attributes help in uniquely identifying the project in repository.
Answer 2 : Find the dropdown and create the object to Select class and try to select the option using
selectByVisibleText, if the option is there, then it will be selected; otherwise, it will throw an exception.
So based on this exception, we can decide whether the element is there or not.
Answer 3: Write an Xpath/Css locator based on the parent(dropdown) and then find a child (the target)
like, //select[@id='some']/option[text()='cherchertech'], if element found, then positive otherwise
negative. We can have a try and catch block here.
XPath axes in selenium are methods to identify those dynamic elements which are not possible to find
by normal XPath method such as ID, Classname, Name, etc.
Axes are so named because they tell about the axis on which elements are lying relative to an
element. The commonly useful XPath axes methods used in Selenium WebDriver are child, parent,
ancestor, sibling, preceding, self, etc.
There are following ways by which we can handle complex and dynamic elements in selenium. They
are as follows:
Class .classname
Stringbuffer alpha = new StringBuffer(), num = new StringBuffer(), spl = new StringBuffer();
if(Character.isDigit(str.charAt(i)))
num.append(str.charAt(i));
else if(Character.isApbhabetic(str.charAt(i))
alpha.append(str.charAt(i));
else spl.append(str.charAt(i));
System.out.println(num);
System.out.println(alpha);
System.out.println(spl);
Str = “I#3need78jal!@swed”
splitStrin(str);
Case 1 (num = 0): This will print the entire String as it does not depend on the
number of words that a String variable has. Thus the output will be all the five words
that we have taken as a String variable.
for(String splits:str.split("\\s",0)) {
System.out.println(splits);
}
System.out.println();
Case 2 (num = 1): This will also print the entire String but in a single line as num is
specified with the value as 1.
System.out.println("This is for num = 1:");
for(String splits:str.split("\\s",1)) {
System.out.println(splits);
}
System.out.println();
Case 3 (num = 2): This will print the String but in two different lines. The first line will
be the first word that comes in a String and the remaining will be printed in the
second line.
Case 4 (num = -1): As we have already discussed, all the zeros and negative num
values will result in the complete decomposition, thus it will also print just like Case
1.
Case 6 (num = 5): As the String has only five words, it will print all the five words in
a new line.
Java String replaceAll() method works in accordance with the regular expression and
based on the regular expression, we are free to choose what type of operation we are going
to have on an input String.
String str = "This is a Testing Website";
Java String replaceFirst() method is used to replace the first occurring character with a
new character.
String str = "PPPPP";
System.out.println(str);
System.out.println(replaceFirst);
Scenario 1–
Here, we have used “Fred*” i.e. for every occurrence of “Fred”, “Fredd”, “Fredx”, “Fredy”
and so on, it will replace each of them with the new String “Ted.” Also, it will replace the
“Freddy” (substring in the input String of the below program) with “Tedy”.
// Initialized a String
String str = "Fred Freddy Franklin Michael Trevor Fredy";
// Replacing the names that start with Fred with the Ted
String replaceAll = str.replaceAll("Fred*", "Ted");
}
}
Output:
Scenario 2 –
Here, we are going to replace a String that starts with a certain character sequence
with a new String. We have used the same input String (as an above scenario), then we
have carried out the regex operation using replaceAll.
// Initialized a String
String str = "Fred Freddy Franklin Michael Trevor Fredy";
// Replacing the entire String that starts with Fred with the Ted
String replaceAll = str.replaceAll("Fred.*", "Ted");
// Printed the Original String
System.out.println("Before ReplaceAll() " + str);
}
}
Output:
Scenario 3 –
String str = "Tony Stark John Jon StarkTony";
Let’s take an example of a String “eat*”. Here, the wildcard character ‘*’ occurs at the last
index. This means that the String will always start with “eat” but it is free to choose the
ending characters.
So, when you try to search with the input String as “eat*” then the search result can be
“eat”, “eaten”, “eatable”, “eating” and so on.
System.out.println(str.contains("java"));
//java is not a part of the main String as it is case sensitive, so false
System.out.println(str.contains("vaJa"));
//vaJa is not a part of main String due to character sequence, so it will return false
System.out.println(str.contains(" "));
//Space is a part of the main String, so it will return true
The second line is a string variable with the null value or no value. There is no String
instance in this case.
Scenario1:
String str1 = "Grand Theft Auto";
String str2 = "Assassin Creed";
String str3 = "Call of Duty";
String str4 = "Need for Speed";
String str5 = "Grand Theft Auto";
System.out.println(str1.compareTo(str2));
// Since 'A' is greater than 'G' by 6 characters, so it will return 6
System.out.println(str2.compareTo(str3));
// Since 'C' is smaller than 'A' by 2 characters, so it will return -2
System.out.println(str3.compareTo(str4));
//Since 'N' is smaller than 'C' by 11 characters, so it will return -11
System.out.println(str4.compareTo(str1));
//Since 'G' is Greater than 'N' by 7 characters, so it will return 7
System.out.println(str1.compareTo(str5));
//Strings are equal
Scenario2:
System.out.println(str1.compareTo(str2));
// Since str2 contains 5 characters more than the str1, output should be -5
System.out.println(str2.compareTo(str1));
// Since str2 contains 5 characters less than the str1, output should be +5
Scenario 3:
String str1 = "";
String str2 = " ";
System.out.println(str1.compareTo(str2));
//Since str2 contains one character more than str1, it will give -1
System.out.println(str2.compareTo(str1));
//Since str1 contains one character less than str1, it will give 1
Scenario 4:
System.out.println(str1.compareTo(str2));
//The ASCII representation of the lowercase and uppercase has a difference of 32
Scenario 5:
A space character has an ASCII value 32 whereas a comma has an ASCII value 44. The
difference between the ASCII value of space and comma is 12.
String str1 = ",";
String str2 = " ";
System.out.println(str1.compareTo(str2));
Scenario 6:
How to find the length of a String by using Java .compareTo() method?
String str1 = "Tony Stark";
String str2 = "";
!ERROR! unexpected operator '=' equals() method does compareTo() does the
the content comparison. comparison based on
ASCII value.
The return type is Boolean. The return type is The return type is Integer.
Boolean.
It uses the reference of the String It does not require the It requires the objects to be
variable, so memory addresses should objects to be logically logically ordered.
be the same when comparing. ordered.
System.out.println(str1.compareTo(str2)); // 0
System.out.println(str1 ==str2); // false
System.out.println(str1.equals(str2)); // true
//First loop will find the 'ClOCK TWER HOTEL' in the first column
for (int i=1;i<=3;i++){
String sValue = null;
sValue =
driver.findElement(By.xpath(".//*[@id='post-2924']/div/table/tbody/
tr[1]/th["+i+"]")).getText();
if(sValue.equalsIgnoreCase(sColValue)){
A burndown chart has two axes, x and y. The horizontal axis represents time while the vertical
axis displays user story points. The rightmost point of the chart indicates the start of a project or
agile sprint while the leftmost point shows its end.
There are two types of burndown charts: Agile burndown charts and sprint burndown
charts.
Agile teams to enable tasks to move quickly use an Agile burndown chart.
Development teams use a sprint burndown chart when working in short sprints.
The ScrumMaster should update the release burndown chart at the end of each sprint.
A burn-down chart shows the amount of work remaining on a project (the remaining effort),
whereas a burn-up chart shows how much work has been completed and the total scope of
the project.
24. Final, Finally and Finalize
Final:
Any variable declare along with final modifier then those variables treated as
final variable.
if we declare final variables along with static will became constants.
public final String name = "foo"; //never change this value
If you declare method as final that method also known as final methods. Final
methods are not overridden. Means we cannot overridden that method in anyway.
public final void add(){
}
public class A{
void add(){
//Can't override
}}
If you declare, class is final that class is also known as final classes.
Final classes are not extended. Means we cannot extends that class in anyway.
public final class indhu{
}
public class classNotAllowed extends indhu {...} //not allowed
Finally:
Finally blocks are followed by try or catch. Finally blocks are compulsory
executable blocks. But finally is useful for more than just exception handling.
It allows the programmer to avoid having cleanup code accidentally bypassed by
a return, continue, or break, Closing streams, network connection, and database
connection. Putting cleanup code in a finally block is always a good practice
even when no exceptions are anticipated
where finally doesn't execute e.g. returning value from finally block, calling
System.exit from try block etc
Finally block always execute, except in case of JVM dies i.e. calling
System.exit() .
lock.lock();
try {
//do stuff
} catch (SomeException se) {
//handle se
} finally {
lock.unlock(); //always executed, even if Exception or Error or se
//here close the database connection and any return statements like that we have to write
}
Finalize():
finalize() is a method which is present in Java.lang.Object class.
Before an object is garbage collected, the garbage collector calls this finalize() of
object. Any unreferenced before destroying if that object having any connections with
database or anything. It will remove the connections and it will call finalize () of object.
It will destroy the object.
If you want to Explicitly call this garbage collector you can use System.gc() or
Runtime.gc() objects are there from a long time the garbage collector will destroy
that objects.
public void finalize() {
//free resources (e.g. unallocate memory)
super.finalize();
}
Private Yes No No No
Private & Protected access modifier cannot be used for classes and interfaces.
A class with a private constructor cannot create an object of the class from any other place
like the main method.
class TestClass{
//private variable and method
private int num=100;
private void printMessage(){System.out.println("Hello java");}
}
public class Main{
public static void main(String args[]){
TestClass obj=new TestClass();
System.out.println(obj.num);//try to access private data member - Compile
Time Error
obj.printMessage();//Accessing private method - Compile Time Error
}
}
The program above gives compilation error as we are trying to access private data
members using the class object.
The following Java program demonstrates the use of getter and setter methods for
private variables in Java.
class DataClass {
private String strname;
// getter method
public String getName() {
return this.strname;
}
// setter method
public void setName(String name) {
this.strname= name;
}
}
public class Main {
public static void main(String[] main){
DataClass d = new DataClass();
As both methods are public, we can easily access them using the object of the class. This
way we can overcome the compilation error that pops up every time when we try to access
the private data members of the class.
Q #1) What are Access Modifiers and Non- Access Modifiers in Java?
Answer: Access modifiers define the visibility or scope of a program entity like a class or a
method or a variable or a constructor. Non-access modifiers define the behavior of an
entity. For example, a synchronized method or block indicates that it can operate in a
multithreading environment; a final variable indicates that it is a constant.
1. Critical –
A defect that has completely blocked the functionality of an application where the user or the tester is
unable to proceed or test anything. If the whole application is inaccessible or down because of a
defect, such a defect is categorized as a critical defect.
For instance– When the login screen of an application is not working and the user is
unable to login, the whole application becomes inaccessible to the user.
2. Major –
When a bug isn’t affecting the whole application but still prevents major
functionalities of a system from working, it becomes a Major defect.
3. Minor –
The behavior of an application is not as expected, but this does not affect
functionality. Usually, minor severity defects have a workaround, so they may not
block a functionality completely (unlike major severity defects where there is no
workaround).
Such minor defects can wait to be fixed until the next release because they are not
restricting the functionality of the application.
For instance, the download link in the Help section of an application is not working.
However, the user is still able to read the document online.
4. Low –
Defects of cosmetic nature that don’t affect the application functionality or UX directly. But they are
valid defects nonetheless.
For instance, spelling mistakes on the webpage. These are valid defects, but they can wait to be
fixed since they are not affecting application functionality.
1. High –
They need resolution as soon as possible, and assigning a high-priority to them ensures
that the time-to-resolution is low. These bugs may affect the whole application.
2. Medium –
The defects, which do not affect business and customers typically, get Medium priority. They are not as
urgent as the high priority defects and can be fixed when the development team has the bandwidth to
take them up. Such bugs can be fixed in either the same release or the next.
3. Low –
The defects which have the least priority for getting fixed, they are fixed after all the high and medium
priority defects are fixed. The fix for low priority defects is usually provided along with some high or
medium priority defects’ fixes.
TEST DESIGN COVERAGE - Total number of requirements mapped to Test Cases / Total
number of Requirements.
AUTOMATION COVERAGE - Number of manual test cases automated / Total number of test cases.
TEST EXECUTION PRODUCTIVITY - Total No of test cases executed/Efforts in Hours spent for execution
of Test Cases.
DEFECT REMOVAL EFFICIENCY - Number of Defects detected before Production /
Total number of Defects Detected.
DEFECT REJECTION - Number of defects that were Invalid / Total number of defects
identified.
An RCA document should include WHY the defect was not caught during the different stages of Testing
and WHAT we could do to avoid this in future.
In Implicit Wait, we
need not specify In Explicit Wait, we need to specify
“ExpectedConditions” “ExpectedConditions” on the element to be
on the element to be located
located
The Fluent Wait in Selenium is used to define maximum time for the web driver to
wait for a condition, as well as the frequency with which we want to check the
condition before throwing an “ElementNotVisibleException” exception. It
checks for the web element at regular intervals until the object is found or
timeout happens.
Let’s consider a scenario where an element is loaded at different intervals of
time. The element might load within 10 seconds, 20 seconds or even more
then that if we declare an explicit wait of 20 seconds. It will wait till the
specified time before throwing an exception. In such scenarios, the fluent wait
is the ideal wait to use as this will try to find the element at different frequency
until it finds it or the final timer runs out.
Write code for Cross Browser Testing
29. Explain Method Overloading and Method
Overriding with Example
If two or more method in a class has same name but different parameters, it is known as
method overloading.
When a method in a sub class has the same name and type signature as a method in its
super class, then the method is known as overridden method. Method overriding is also referred
to as runtime polymorphism. The key benefit of overriding is the ability to define the method that’s
specific to a particular subclass type.
class Animal
{
public void eat()
{
System.out.println(“Generic Animal eating”);
}
}
class Dog extends Animal
{
public void eat() //eat() method overriden by Dog class.
{
System.out.println(“Dog eat meat”);
}
}
As you can see here Dog class gives it own implementation of eat() method. Method
must have same name and same type signature.
NOTE*: Static methods cannot be overridden because a static method is bounded with
the class whereas instance method is bounded with an object
Represent this keyword mainly represents the On other hand super keyword
and current instance of a class. represents the current instance of a
1
Reference parent class.
Interaction this keyword used to call default super keyword used to call default
with class constructor of the same class. constructor of the parent class.
2
constructor
Method this keyword used to access methods One can access the method of parent
accessibility of the current class as it has reference class with the help of super keyword.
3
of current class.
Sr. No. Key this super
Static this keyword can be referred from On other hand super keyword can't be
context static context i.e can be invoked from referred from static context i.e can't
static instance. For instance we can be invoked from static instance. For
write System.out.println(this.x) instance we cannot write
4 which will print value of x without System.out.println(super.x) this will
any compilation or runtime error. leads to compile time error.
class A {
public int x, y;
public A(int x, int y) {
this.x = x;
this.y = y;
}
}
class B extends A {
public int x, y;
public B() {
this(0, 0);
}
class Point {
public static void main(String[] args) {
B obj = new B();
obj.print();
obj = new B(1, 2);
obj.print();
}
}
Output
Static blocks - If you need to do the computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}
Static variables
When a variable is declared as static, then a single copy of the variable is created and shared among all
objects at the class level. Static variables are, essentially, global variables. All instances of the class share
the same static variable.
Static methods
When a method is declared with the static keyword, it is known as the static method. The most common
example of a static method is the main( ) method. As discussed above, Any static member can be
accessed before any objects of its class are created, and without reference to any object. Methods
declared as static have several restrictions:
// instance variable
int b = 20;
// static method
static void m1 ()
{ a = 20;
System.out.println("from m1");
// Cannot make a static reference to the non-static method m2() from the type Test
m2 (); // compilation error
// Cannot use super in a static context
System.out.println(super.a); // compiler error }
// instance method
void m2()
{ System.out.println("from m2"); }
// Student class
class Student {
String name;
int rollNo;
// static variable
static String cllgName;
this.rollNo = setRollNo();
}
// static method
static void setCllg(String name) { cllgName = name; }
// instance method
void getStudentInfo()
{
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);
// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");
s1.getStudentInfo();
s2.getStudentInfo();
}}
Static Classes
A class can be made static only if it is a nested class. We cannot declare a top-level class with a static
modifier but can declare nested classes as static. Such types of classes are called Nested static classes.
Nested static class doesn’t need a reference of Outer class. In this case, a static class cannot access non-
static members of the Outer class.
An instance of an inner class cannot be created without an instance of the outer class. Therefore, an
inner class instance can access all of the members of its outer class, without using a reference to the
outer class instance. For this reason, inner classes can help make programs simple and concise.
A static nested class may be instantiated without instantiating its outer class.
Inner classes can access both static and non-static members of the outer class. A static class can access
only the static members of the outer class.
In an automation framework, WebDriver and WebElement required to be thread-safe to be able to
execute test cases in parallel.
// Only static members of Outer class is directly accessible in nested static class
public void printMessage()
{
// Try making 'message' a non-static variable, there will be compiler error
System.out.println("Message from nested static class: " + msg); }
}
// Non-static nested class also called Inner class
public class InnerClass {
// Both static and non-static members of Outer class are accessible in this Inner class
public void display()
{ // Print statement whenever this method is called
System.out.println("Message from non-static nested class: "+ msg);
} } }
// Note: In order to create instance of Inner class we need an Outer class instance
// Creating Outer class instance for creating non-static nested class
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner
= outer.new InnerClass();
// We can also combine above steps in one step to create instance of Inner class
OuterClass.InnerClass innerObject
= new OuterClass().new InnerClass();
Dependencies in Pom.xml
32. Write code for fetching data from Excel
String filepath= "excelsheet.xlsx";
FileInputStream f = new FileInputStream(new File(filepath));
Workbook wbk = new XSSFWorkbook(f);
Sheet sh1 = wbk.getSheetAt(0);
Iterator<Row> i = sh1.iterator();
while (i.hasNext())
{
Row r = i.next();
Iterator<Cell> cell = nextRow.cellIterator();
while (cell.hasNext())
{
Cell c = cellIterator.next();
switch (c.getCellType())
{
case Cell.CELL_TYPE_STRING:
System.out.print(c.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(c.getNumericCellValue());
break;
}
System.out.print(" : ");
}
System.out.println();
}
wbk.close();
f.close();
}
class FileReader_example {
int p;
while((p=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
import java.io.*;
class Sample
try
fw.close();
System.out.println("congo...");
Whereas, in the case of “Verify”, the test method continues execution even after the failure of an
assertion statement. Although the test method will still be marked as failed but the remaining
statements of the test method will be executed normally.
In TestNG, the Verify functionality is provided by means of the Soft Assertions or using SoftAssert class.
ASSERT
We use Assert when we have to validate critical functionality. If the feature fails then this makes the
execution of further statements irrelevant. Hence, the test method is aborted as soon as failure occurs.
@Test
public void assertionTest(){
//Assertion Passing
Assert.assertTrue(1+2 == 3);
System.out.println("Passing 1");
//Assertion failing
Assert.fail("Failing second assertion");
System.out.println("Failing 2");
}
Output
Passing 1
FAILED: assertionTest
java.lang.AssertionError: Failing second assertion
Here, we can observe that only the text “Passing 1” gets printed. The second assertion aborts the test
method as it fails to prevent further statements from getting executed.
VERIFY
At times, we might require the test method to continue execution even after the failure of the assertion
statements. In TestNG, Verify is implemented using SoftAssert class.
In the case of SoftAssert, all the statements in the test method are executed (including multiple
assertions). Once, all the statements are executed, the test results are collated based on the assertion
results. And then the tests are marked as passed or fail.
Example
@Test
public void softAssertionTest(){
//Assertion failing
softAssert.fail("Failing first assertion");
System.out.println("Failing 1");
//Assertion failing
softAssert.fail("Failing second assertion");
System.out.println("Failing 2");
//Collates the assertion results and marks test as pass or fail
softAssert.assertAll();
}
Output
Failing 1
Failing 2
FAILED: softAssertionTest
java.lang.AssertionError: The following asserts failed:
Failing first assertion,
Failing second assertion
Here, we can see that even though both the test methods are bound to fail. Still the test continues to
execute.
// for string 1
System.out.print("String 1 :");
if (isPalindrome(str))
System.out.print("It is a palindrome");
else
System.out.print("It is not a palindrome");
// for string 2
System.out.print("String 2 :");
if (isPalindrome(str2))
System.out.print("It is a palindrome");
else
System.out.print("It is not a palindrome");
}
}
In the first step, we have to convert the string into a character array.
Calculate the size of the array.
Call removeDuplicates() method by passing the character array and the length.
Traverse all the characters present in the character array.
Check whether the str[i] is present before or not. If it is not present before, add it to the result.
//Import packages
import java.util.*;
//Import packages
import java.util.Arrays;
//Create RemoveDuplicatesExample2 class
public class RemoveDuplicatesExample2
{
//Create removeDuplicates() method to remove duplicate characters from sorted array
static void removeDuplicates(String str)
{
//index to track the location of next character(Input string)
int index1 = 1;
//Check whether the character is present before it or not. If it is not present before, add it to the
result string
while (index1 != arr.length)
{
if(arr[index1] != arr[index1-1])
{
arr[index2] = arr[index1];
index2++;
}
index1++;
In addition to the existing answers, another factor in ROI is how often the test cases need to be run.
If automating the test cases will take you 500 hours, they need to be run once a year, and it takes an
hour to run each test case manually, by the time the automation has "earned back" the initial
development time, the software is likely to be obsolete.
If, on the other hand, you need to run the same test cases three times a day (after each build), then it's
worth doing, because you will be into positive ROI within a year
Number of moving parts - how many different aspects of the software does your test case
need to interact with. If you are checking straight database input, your test case would be simpler than if
there is data manipulation downstream of the data entry. Similarly, entering data is a lot simpler than
performing tax calculations.
Preconditions - the more things that need to be in place for your test case to run, the more
complex your automation or framework needs to be.
Maturity of framework - the framework should be mature enough that adding a test case for
a new feature could be as simple as one new function, one line of code to call that function, and half-a-
dozen rows of data added to the run files and baselines. Without that, you are looking at a much longer
time to automate and likely more repeated code.
Postcondition validations - the more changes the test case makes, the more validations you
will need to perform on completion of the test case. You may have software that has a single button-
click action to kick off a complex process with dozens of validations needed. That will take more time to
automate.
Existing automation - it is often faster and easier to add to existing automation than to build
from scratch. If you can make use of existing test harnesses, you can call and possibly expand on already
built helper functions, which reduces your automation time.
Most Important - Don't forget to include time to test and deploy your automation. In my
experience building it is the fastest part. Testing it to ensure it's stable and does not generate false
positives or false negatives and getting it deployed to run on a regular basis takes a lot longer.
38. How to perform Right Click
Double click in Selenium using Actions class
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id("ID"));
actions.doubleClick(elementLocator).perform();
Right-click in Selenium
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id("ID"));
actions.contextClick(elementLocator).perform();
@Before
public void setUp() throws Exception {
// Selenium version 3 beta releases require system property set up
System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"Selenium\\
geckodriver-v0.10.0-win64\\geckodriver.exe");
// Create a new instance for the class FirefoxDriver
// that implements WebDriver interface
driver = new FirefoxDriver();
// Implicit wait for 5 seconds
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// Assign the URL to be invoked to a String variable
baseUrl = " https://chandanachaitanya.github.io/selenium-practice-site/";
}
@Test
public void testPageTitle() throws Exception {
// Open baseUrl in Firefox browser window
driver.get(baseUrl);
//Printing table contents to console for fixed row and column numbers
for(int i=2; i<=6; i++){
for(int j=1; j<=4; j++){
System.out.print(driver.findElement(By.
} //End of @Test
@After
public void tearDown() throws Exception {
// Close the Firefox browser
driver.close();
}
}
A. Right-click on the specific element and check all the options. If you find an option like This
Frame, view Frame source or Reload Frame, it means the page includes frames.
B. Similar to the first step, right-click on the page and click on View Page Source.
On the page source, search for “iframe-tags”. If you find any iframe tags, it means the page
includes iframes.
switchTo.frame(int frame number): Defining the frame index number, the Driver will switch to
that specific frame
switchTo.frame(string frameNameOrId): Defining the frame element or Id, the Driver will
switch to that specific frame
switchTo.frame(WebElement frameElement): Defining the frame web element, the Driver will
switch to that specific frame
Executing JavaScript
JavascriptExecutor exe = (JavascriptExecutor) driver;
Integer noOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
System.out.println("No. of iframes on the page are " + numberOfFrames);
Finding the total number of elements that have the tag “iframe”
List<WebElement> iframeElements = driver.findElements(By.tagName("iframeResult"));
System.out.println("Total number of iframes are " + iframeElements.size());
driver.switchTo().frame("id"); // Switch By ID
driver.switchTo().defaultContent();
import java.io.*;
import java.util.*;
class GFG {
final static String filePath = "F:/Serialisation/write.txt";
public static void main(String[] args)
{
// read text file to HashMap
Map<String, String> mapFromFile = HashMapFromTextFile();
return map;
}
}
if(charCountMap.containsKey(c))
charCountMap.put(c, charCountMap.get(c)+1);
else
//If char 'c' is not present in charCountMap, putting 'c' into charCountMap with 1 as it's value
charCountMap.put(c, 1);
System.out.println(inputString+" : "+charCountMap);
characterCount("All Is Well");
}
Java J2EE Java JSP J2EE : { empty space=4, P=1, a=4, 2=2, S=1, E=4, v=2, J=5}
All Is Well : { empty space= 2, A=1, s=1, e=1, W=1, I=1, l=4}
Done And Gone : { empty space= 2, A=1, D=1, d=1, e=2, G=1, n=3, o=2}
1. Above program is a case sensitive i.e it treats ‘A’ and ‘a’ as two
different characters. If you want your program not to be case sensitive,
convert the input string to either lowercase or uppercase
using toLowerCase() or toUpperCase() methods.
2. If you don’t want to count white spaces then remove white spaces
from inputString using inputString.replaceAll("\\s+", "")
Write code for nested drop-down, You have to check all the
values in the dropdown, All permutation, and combination
Advantages of Selenium
How to check if a checkbox is displayed
If the element is not present, how will you print the Element
that is not present in the message?
What all exceptions you have faced
What all difficulties you have faced in Selenium
What all TestNG Annotations you have used in the project
Where will you maintain the code?
What all Collections, you have used in your project
How to run multiple test cases
What are Primitive and Non-primitive Data Types?
What are JDK, JRE, and JVM
Settings.xml in Maven
Eliminate first and last string from array and print
What is Encapsulation
What is the use of build() and perform() in Actions
How you will check the actual vs expected result
Xpath Axes, Ex: Following
Automate Menu and Sub Menu and click on a link in Sub
Menu and navigate to the page and click on an element
Syntax for Alerts
Question asked in an interview in different organizations for 5 years of exp in last one
month.
If you want to schedule your build every 5 minutes, this will do the job :
*/5 * * * *
If you want to schedule your build every day at 1h00, this will do the job :
01***
Create a Simple Jenkins Job
Click Build Now. The job will run and complete almost
immediately. Next, click the build number to see your results.
Next, click on Console Output, and you’ll see the shell
message.
Your job is ready for scheduling!
Add a Schedule to a Jenkins Job
Save the job again and wait a few minutes. Depending on the
value Jenkins selects for H, the job will run after a few
minutes.
Wait for a bit longer and you will see that it continues to run
every five minutes.
Apart from Jenkins what ci/cd tool you can use.
What is an effective pom in maven?
How many different build phases are available in maven.
How to pass TestNG in maven file.
How to create a profile in maven and execute the same.
How the optimize ur current framework.
What has expected conditions in explicit wait is it a class or
interface.
44. How to take screenshot of failed TC.
To do this, first we need to create a class and then
implement TestNG 'ITestListener'. We will have a method
called 'onTestFailure'. We need to add the code to take the
screen shot in this method. Instead of just taking the screen
shot, we will get the Test method name and take a screen shot
with test name and place it is destination folder.
package com.pack.listeners;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import com.pack.sample.TestBase;
WebDriver driver=null;
@Override
String methodName=result.getName().toString().trim();
takeScreenShot(methodName, driver);
//The below method will save the screen shot in d drive with test method name
try {
} catch (IOException e) {
e.printStackTrace();
Before executing the above program, we need to add TestListener class in testng.xml file as below:
<listeners>
<listener class-name="com.pack.listeners.TestListener"/>
</listeners>
Take Screenshot and place it in a folder with Test Class name
As we are taking screen shots on failure, we need to add logic in creating a screen shot and naming it
with test name and place it in its test class name respectively.
package com.pack.listeners;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import com.pack.sample.TestBase;
if (driver != null) {
String imagePath = ".." + fileSeperator + "Screenshots"
+ fileSeperator + "Results" + fileSeperator + testClassName
+ fileSeperator
+ takeScreenShot(driver, screenShotName, testClassName);
System.out.println("Screenshot can be found : " + imagePath);
}
}
1. After the first run of an automated test run. Right click on Project
– Click on Refresh
2. A folder will be generated named “test-output” folder. Inside
“test-output” folder, you could find “testng-failed.xml”
3. Run “testng-failed.xml” to execute the failed test cases again.
package softwareTestingMaterial;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
//This method will be called everytime a test fails. It will return TRUE if a test fails and need to be
retried, else it returns FALSE
package softwareTestingMaterial;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.IRetryAnalyzer;
import org.testng.annotations.ITestAnnotation;
@Override
public void transform(ITestAnnotation testannotation, Class testClass, Constructor
testConstructor, Method testMethod) {
IRetryAnalyzer retry = testannotation.getRetryAnalyzer();
if (retry == null) {
testannotation.setRetryAnalyzer(RetryFailedTestCases.class);
}
}
}
Include below mentioned Listener to testng.xml file. Below mentioned syntax is to add Listener for
RetryListnereClass
<listeners>
<listener class-name="softwareTestingMaterial.RetryListenerClass"/>
</listeners>
<listeners>
<listener class-name="softwareTestingMaterial.RetryListenerClass"/>
</listeners>
<test name="Test1">
<classes>
<class name="softwareTestingMaterial.Test1" />
</classes>
</test> <!-- Test -->
<test name="Test2">
<classes>
<class name="softwareTestingMaterial.Test2" />
</classes>
</test> <!-- Test -->
Testcase 1:
package softwareTestingMaterial;
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void test1(){
System.out.println("Test 1");
Assert.assertTrue(true);
}
}
Testcase 2:
package softwareTestingMaterial;
import org.testng.Assert;
import org.testng.annotations.Test;
Execute the testng.xml. Here is the output which I got. You could see in the below mentioned result that
the Test 2 is executed three times as we have mentioned ‘maxRetryCnt = 2’. Even though we have just 2
tests, we could find total test runs are 4 in the result.
[TestNG] Running:
D:\Selenium\workspace\SeleniumProject\testng.xml
Test 1
Test 2
Retrying test2 again and the count is 1
Test 2
Retrying test2 again and the count is 2
Test 2
===============================================
Everjobs Suite
Total tests run: 4, Failures: 1, Skips: 2
===============================================
1) Simple Alert
2) Prompt Alert.
This Prompt Alert asks some input from the user and Selenium webdriver can enter the text using
sendkeys(” input…. “).
3) Confirmation Alert.
@Test
public void testWindowAlert() throws Exception{
rb.keyPress(KeyEvent.VK_SHIFT);
rb.keyPress(KeyEvent.VK_SEMICOLON);
rb.keyRelease(KeyEvent.VK_SEMICOLON);
rb.keyRelease(KeyEvent.VK_SHIFT);
rb.keyPress(KeyEvent.VK_BACK_SLASH);
rb.keyRelease(KeyEvent.VK_BACK_SLASH);
Thread.sleep(2000);
rb.keyPress(KeyEvent.VK_P);
rb.keyRelease(KeyEvent.VK_P);
rb.keyPress(KeyEvent.VK_I);
rb.keyRelease(KeyEvent.VK_I);
rb.keyPress(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_C);
Thread.sleep(2000);
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
You can customize JIRA software for test management in either of the ways:
Using the “User story”
Adding a “Test Case” issue
4. Adaptavist Test Management - detail test steps, reuse steps from other test cases, time saving
and ensuring standardization. The simple, functional test case interface also allows users to drag and
drop test steps.
5. Tracing a test case from start to go-live is a critical part of any testing lifecycle; ensuring nothing is
missing between teams.
6. Design a reusable and modular test case library - use hierarchical folders to reuse test cases and
test scripts across all your projects, releases and sprints.
Test plan and estimation - The Test objective, test approach, test scope, entry
& exit criteria, types & levels of testing, milestones, staffing, etc should be
mentioned here in a detailed manner.
Estimation is defining how long each step will occur in testing along with the
overall cost.
Test scenario - Two Techniques for the scenario:
#1) Use Case - A use case is a written description of how users will perform tasks
on your website. It outlines, from a user's point of view, a system's behavior as it
responds to a request. Each use case is represented as a sequence of simple steps,
beginning with a user's goal and ending when that goal is fulfilled.
#2) ACE (Activity Component Element) - The Activity Component Element process
breaks the business requirements into activities. Example:
In general, we book a ticket by filling the passenger details, gender, etc. Hence we
need to validate the following fields which thereby become scenarios.
RTM
To map every requirement with the appropriate test case. Checking if we have
covered all the requirements in our test cases or not. Helps in rework or the next
successive releases of a project. Client can easily check our coverage status and
know our testing process.
Incident report
While performing formal execution if a user finds defects, then an Incident report (IR)
is raised. This means that there is a defect and thus the execution is to be stopped.
We now need to raise an incident report to the client for asking them permission to
execute the error areas again as a separate test case.
This indeed is a black mark and is not expected from a tester. All the defects have to
be found in the dry run itself. If it is missed and found in formal execution, then it
becomes an IR.
Example:-
If I miss certain functionality in mobile testing say “screensaver change” option. Then
while executing a test case I get locked and I will not be able to proceed further
because of this option. Then I raise an IR and write a separate test case to execute
the screensaver option.
How do you see automation growth in the next five years?