SEL QA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 107

Tell me about the work you’ve been doing recently.

What’s
the most interesting bug that you’ve found, and why?

What kind of challenges does testing present? Can you tell


me about some specific software testing challenges you’ve
faced, and how you overcame them?

Have you encountered any challenges working with your


colleagues? Tell me about a specific instance when you were
in a difficult situation, and how you dealt with it.
How about situations where you have to make decisions…
Have you ever made a bad decision? What contributed to
you making that decision? How did you deal with the
consequences?
How have you added value to the organisations you’ve
worked with? Can you give me a specific example from your
last or current position?
What process are you using for testing currently? Can you
describe how you might improve it?
What kind of tests have you been doing? What do you enjoy
about them? How do you develop those tests?
When you perform a test, what steps do you take? What’s
your process?
1. Have you ever written a test plan? What would you put
in one?
A test plan is a document that sets out the scope, approach, and schedule of intended testing activities.
The test plan may also list the resources the software tester needs to function effectively.

The test plan usually includes the following information:

1. The overall objective of the testing effort.


2. A detailed outline of how testing will be conducted (the test approach).
3. The features, applications, or components to be tested.
4. Detailed scheduling and resource allocation plans for testers and developers throughout all stages of
testing.

 Concise. Your test plan should be no longer than one page with bullet points.

 Organized. Make sure all the information is logically grouped.

 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.

 Accurate. Make sure all the information you've included is accurate.

2. How do you know when it’s time to stop testing?


Testing can be stopped when:

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?

What’s the role of risk in your testing? How do you analyse


and measure it?
3. Do you measure how effective (or not) your testing is?
What metrics do you use?
Test effectiveness can be calculated using the below formula:

 Test Effectiveness = Number of valid bugs fixed / ( Bugs injected+ number of


bugs escaped)*100
 Test efficiency = (Total number of defects found in unit+integration+system) /
(Total number of defects found in unit+integration+system+User acceptance
testing)*100

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)

3. Will scope test scenario and test data.

Have you automated any of your tests? How so?


What’s your favorite testing tool? Why? If some technical
constraint meant you were unable to use it, what would you
do instead?
How do you know when you (or your automation) has found
a bug? What makes it a bug? Are some bugs more
important than others? How do you report them?
What do you do if the developers decide the bug is not a
bug?
5. Testing can be challenging. What keeps you motivated?
 Software Testing is about looking at a product from different angles, with
different perspectives and testing it with different expectations.

 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.

How do you stay at the top of your game? What self-learning


do you do?
What have you been criticized for in the past? How did you
respond to that criticism? What did you do about it?
Describe the characteristics of your ideal boss, and why.
Selenium Tricky Interview Questions

1. Write code for Action class


Actions class is an ability provided by Selenium for handling keyboard and mouse events. In Selenium
WebDriver, handling these events includes operations such as drag and drop, clicking on multiple
elements with the control key, among others.

Actions action = new Actions (driver);


action.moveToElement (element).click ().perform ();

Mouse Actions in Selenium:


 doubleClick(): Performs double click on the element
 clickAndHold(): Performs long click on the mouse without releasing it
 dragAndDrop(): Drags the element from one point and drops to another
 moveToElement(): Shifts the mouse pointer to the center of the element
 contextClick(): Performs right-click on the mouse
Keyboard Actions in Selenium:
 sendKeys(): Sends a series of keys to the element
 keyUp(): Performs key release
 keyDown(): Performs keypress without release

//Double click on element


WebElement trialaction = driver.findElement (By.xpath ("//a[@id='free-trial-link-anchor']"));
a.doubleClick(trialaction).perform();
//Perform Mouse Hover Action on the Web Element
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\
chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.browserstack.com/");
((JavascriptExecutor) driver).executeScript("scroll(0,300)");
Actions ac = new Actions(driver);
WebElement live= driver.findElement(By.cssSelector("div.product-cards-wrapper--click
a[title='Live']"));
ac.moveToElement(live).build().perform();
WebElement automate= driver.findElement(By.cssSelector("div.product-cards-wrapper--click
a[title='App Automate']"));
automate.click();

//using click action method


driver.get("https://www.browserstack.com/");
Actions action = new Actions(driver);
element = driver.findElement(By.linkText("Get started free"));
action.moveToElement(element).click();

2. Write code for positive and negative scenarios for Alerts


A positive test case tests that a system does what it is supposed to. Example:
will allow you to login when valid credentials are supplied.

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");

3. Write code for handling multiple windows


A window in any browser is the main webpage on which the user is landed after hitting a link/URL. Such
a window in Selenium is referred to as the parent window also known as the main window that opens
when the Selenium WebDriver session is created and has all the focus of the WebDriver.

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.

String parent=driver.getWindowHandle(); // It will return the parent window name as a String

Set<String> s=driver.getWindowHandles(); //Get the handles of all the windows that are currently open
using the command

Iterator<String> win= s.iterator(); // Now iterate using Iterator

while(win.hasNext())

{String child_window=win.next();

if(!parent.equals(child_window))

{driver.switchTo().window(child_window); //switch to the parent window

System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close(); }}

driver.switchTo().window(parent); }} //switch to the parent window

Handling Tab in Selenium


ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));

driver.close();

driver.switchTo().window(tabs2.get(0));

4. Find odd number


public class OddEvenInArrayExample {

public static void main(String args[]) {


int a[]={1,2,5,6,3,2};
System.out.println("Odd Numbers:");
for(int i=0;i<a.length;i++) {
if(a[i]%2!=0) {
System.out.println(a[i]);
}
}
System.out.println("Even Numbers:");
for(int i=0;i<a.length;i++) {
if(a[i]%2==0) {
System.out.println(a[i]);
}
}
}
}

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.

6. Difference between get() and navigate().to()


The differences between get() and navigate() methods are listed below.

sl.no get() navigate()


.

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();

7. Write code to click on the Check box which is inside the


Dynamic Table
following-sibling -
//td[contains(text(),'Dog')]/following-sibling::td/input[@type='checkbox']
/following-sibling will locate all siblings after the current node

preceding-sibling - //td[contains(text(),'Cow')]/preceding-
sibling::td/input[@type='checkbox']

//Locating element using preceding-sibling In XPath.


driver.findElement(By.xpath("//td[contains(text(),'Cow')]/preceding-
sibling::td/input[@type='checkbox']")).click();
//Locating element using following-sibling In XPath.
driver.findElement(By.xpath("//td[contains(text(),'Dog')]/following-
sibling::td/input[@type='checkbox']")).click();

8. How to handle a dynamic WebTable


//Method-1:
String before_xpath = "//*[@id='vContactsForm']/table/tbody/tr[";
String after_xpath = "]/td[2]/a";

for(int i=4; i<=7; i++){


String name = driver.findElement(By.xpath(before_xpath + i + after_xpath)).getText();
System.out.println(name);
if(name.contains("test2 test2")){
//i=6
//*[@id='vContactsForm']/table/tbody/tr[6]/td[1]/input

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();

9. Copy all data from a webtable and write in excel sheet


WebElement statusTable = browser.findElement(By.id("projectstatus")); //get the table
List<WebElement> allRows = statusTable.findElements(By.tagName("tr")); //Get all the
rows in the table
int rowSize = allRows.size(); //Get the size(row no) of allRows
System.out.println(rowSize);
File file = new File("e:\\Testing_emi.xls"); // locate the test xls file
FileInputStream fis = new FileInputStream(file); // create input stream
HSSFWorkbook wb = new HSSFWorkbook(fis); // create workbook
HSSFSheet sheet1 = wb.getSheet("Sheet1"); // get sheet
HSSFRow row; // get rows
for (int i=0; i<rowSize; i++)
{
WebElement webRow = allRows.get(i);
List<WebElement> allCells = webRow.findElements(By.tagName("td")); //Get all
cell values in each row
//System.out.println(allCells.size());
if(allCells.size() > 1)
{
HSSFRow excelRow = sheet1.createRow(i);

for (int j=0; j<allCells.size(); j++)


{
WebElement webCell = allCells.get(j);
String text = webCell.getText();
if(text.length()>2)
{
Cell excelCell = excelRow.createCell();
excelCell.setValue(webCell.getText());
} } } }
sheet1.close();
10. Write code for taking Screenshot
//Convert webdriver to TakeScreenshot
File screenshotFile = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
//Copy the file to a location and use try catch block to handle exception
try {
FileUtils.copyFile(screenshot, new File("C:\\
projectScreenshots\\homePageScreenshot.png"));
} catch (IOException e) {
System.out.println(e.getMessage());
}

// capture screenshot and store the image


Screenshot s=new
AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeSc
reenshot(driver);
ImageIO.write(s.getImage(),"PNG",new File("C:\\
projectScreenshots\\fullPageScreenshot.png"));

11. Explains Maps in Java


Maps are perfect to use for key-value association mapping such as
dictionaries. The maps are used to perform lookups by keys or when someone
wants to retrieve and update elements by keys. Some common scenarios are
as follows:
 A map of error codes and their descriptions.
 A map of zip codes and cities.
 A map of managers and employees. Each manager (key) is associated with
a list of employees (value) he manages.
 A map of classes and students. Each class (key) is associated with a list of
students (value).

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.

13. Which is the correct Xpath for this code (Lot of


questions on Xpath)

14. How do you check an option is present in a dropdown or


not ?
Answer 1: Find the dropdown and Create an object to the Select class and Retrieve all options using
getOptions() method and Iterate all options and compare the text.

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.

14. Xpath methods Ex: Starts-with & Contains


Contains() and starts-with() function in XPath is used when we are
familiar with the pattern of dynamically changing attribute’s value of
an element on HTML pages.
It also works when we want to write XPath on the basis of a partial pattern of any of attribute.

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:

 Basic XPath - //input[@name = 'user-message']

 XPath Contains - //input[contains(@name,'btnK')]"));

 XPath Starts-with - //input[starts-with(@name, 'keyword')], //span[starts-with(@class, 'field-


submit-text')]

 XPath Ends-with - //input[ends-with(@attribute, ‘name’)]

 Using “OR” Statement - //input[@value = 'Log In' or @type = 'submit']

 Using “AND” Statement - //button[@type = 'submit' and @id = 'u_0_19']

 XPath Text - //div[text() = 'Recent logins']

 XPath link - //a[text() = 'Gmail']

15. The syntax for the CSS selector


The CSS Selector combines an element selector and a selector value that can identify particular
elements on a web page. Like XPath, CSS selector can be used to locate web elements without ID, class,
or Name.
There are 5 types of CSS Selectors in Selenium tests-
1. ID
2. Class
3. Attribute
4. Sub-String
5. Inner String
ID #idname

Class .classname

1) Using Absolute Path CSS Selector


You should use > sign to reach an element directly. (Note: For XPath, we use / sign for this.)
Example
Syntax: form>div>input

2) Using Non-Absolute Path CSS Selector


You should use white space between tags to locate the element. Use “.” for class and “#” for id.
Example
Syntax: form .form-group #user-message
3) Using Tag Name CSS Selector in Selenium
You can write the tag name directly like “form”, “div”, “img”,”body”, etc. As below figure, I wrote the
“form” tag to locate the form element.
(Note: For XPath we use //tagname for this.)
Example

4) Using Tag & Attribute & Value Trio


You can use tag[attribute=’value’] syntax.
(Note: For XPath we use tag[@attribute=’value’] for this.)
Example
Syntax: input[id=’user-message’]

5) Using Containing Text of an Attribute


You can use tag[attribute*=’containing text’] syntax.
(Note: For XPath we use tag[contains((@attribute,’containing text’)] for this.)
Example
Syntax: input[id*=’er-messa’]
6) Using Starting Text of an Attribute
You can use tag[attribute^=’starting text’] syntax.
(Note: For XPath we use tag[starts-with( @attribute, ‘starting text’)] for this.)
Example
Syntax: input[id^=’user’]

7) Using Ending Text of an Attribute


You can use tag[attribute$=’ending text’] syntax.
Example
Syntax: input[id$=’message’]

8) Using Comma Operator to Implement OR Operation


You can use “,” operator between two CSS locator statements.
Example
Syntax: form#get-input,input#user-message

8) Using Comma Operator to Implement OR Operation


You can use “,” operator between two CSS locator statements.
Example
Syntax: form#get-input,input#user-message

9) Using Tag and ID CSS Selector in Selenium


You can use “Tag#Id”
Example
Syntax: input#user-message

10) Using Tag and Class CSS Selector in Selenium


You can use “Tag.Class”
Example
Syntax: input.form-control
11) Using first-of-type CSS Selector in Selenium
You can use “Tag:first-of-type”. It will select the first tag element.
Example
Syntax: .tree-branch>ul>li:first-of-type
12) Using last-of-type CSS Selector in Selenium
You can use “Tag:last-of-type”. It will select the last tag element.
Example
Syntax: .tree-branch>ul>li:first-of-type
Note: If you want to find the last element or child you can use the below locators.
 Tag:nth-last-of-type(n)
 Tag:nth-last-child(n)

13) Using *:last-of-type CSS Selector in Selenium


You can use “*last-of-type”. It will select the last child of the parent tag.
Example
Syntax: .tree-branch>ul>*:last-of-type (Selects the last child of parent tag “ul”.)
14) Using tag:nth-of-type(n) CSS Selector in Selenium
You can use “tag:nth-of-type(n)”. It will select the nth tag element of the list.
Example
Syntax: .tree-branch>ul>li:nth-of-type(3) (Selects 3rd li element.)
Note: If you don’t specify a tag as *:nth-of-type(3) it will allow you to select the third child.
15) Using tag:nth-child(n) CSS Selector in Selenium
You can use “tag:nth-child(n)”. It will select the nth child.
Example
Syntax: .tree-branch>ul>li:nth-child(3) (It will select the nth child.)
16) Using Sibling “+” Operator CSS Selector in Selenium
You can use “E1+ E2“. First, it finds E1 then selects E2.
Sample HTML:
<ul id="Cars">
<li id="mercedes">Mercedes made in Germany!</li>
<li>BMW</li>
<li>Porsche</li>
</ul>
Syntax: li#mercedes + li
‘li#automation + li‘ will first go to li element with id ‘mercedes’ and then select its adjacent li which is
the ‘BMW’ list item.
Example
Syntax: .tree-branch>ul>li:nth-child(3) + li (It will select the next element.)
17) Exclude a CSS Class Name in Selenium CSS Locators
You can exclude any of the class names with :not(.class-name) syntax.
Example:
.btn.btn-info.pull-right:not(.xs-mt-0)
The above selector excludes “xs-mt-o” class and selects the below the line as shown below figure.

16. How to identify dynamic images


1. Absolute Path method. This is the easiest way to solve the issue.
2. Use Relative XPath using contains or starts with text.
3. Identify by index.
4. Use Multiple attributes to locate an element.
From a given string, separate characters, integers, and
special characters and store in a separate variable and print
them
Class test {

static void spitString(String str)

Stringbuffer alpha = new StringBuffer(), num = new StringBuffer(), spl = new StringBuffer();

for(i=0; i<str.length(); i++)

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);

Pubic static void main(String args[])

Str = “I#3need78jal!@swed”

splitStrin(str);

Remove duplicates from ArrayList


17. Print all the frame names
public void getIframe(final WebDriver driver, final String id) {
final List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
for (WebElement iframe : iframes) {
if (iframe.getAttribute("id").equals(id)) {
// TODO your stuff.
}
}
}

18. What is the return type of split() ?


Java String Split() decomposes or splits the invoking string into parts where each
part is delimited by the BRE (Basic Regular Expression) that we pass in the regEx. It
returns an array. of type Strings.
The String “\\s” is a basic regular expression (BRE) in Java which means
whitespaces.
String str = "This is an example";
String[] splits = str.split("\\s");
//using the regular expression “\\s”, we have split the String wherever whitespace
occurred.
String str = "SoftwareEngineerTestingEngineerHelp";
String[] splits = str.split("Engineer");
//substring “Engineer” as delimiter

String str = "scare";


String[] splits = str.split("e");
//This regEx splits the String on ‘e’

Java Split RegEx With Length


System.out.println("This is for num = 0:");

 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.

System.out.println("This is for num = 2:");


for(String splits:str.split("\\s",2)) {
System.out.println(splits);
}
System.out.println();

 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.

System.out.println("This is for num = -1:");


for(String splits:str.split("\\s",-1)) {
System.out.println(splits);
}
System.out.println();

 Case 5 (num = -2): Same as Case 4, it is also a negative value.

System.out.println("This is for num = -2:");


for(String splits:str.split("\\s",-2)) {
System.out.println(splits);
}
System.out.println();

 Case 6 (num = 5): As the String has only five words, it will print all the five words in
a new line.

System.out.println("This is for num = 5:");


for(String splits:str.split("\\s",5)) {
System.out.println(splits);
}
Q #4) How to split a string in Java without delimiter or How to split each character in
Java?
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will
split the entire String into individual characters.
package codes;

public class StringSplit {


public static void main(String[] args) {

for(String str : "Federer".split(""))


System.out.println(str);
}
}
Output:

Q #5) How to split a String by Space?


for(String str : "Software Engineer".split(" "))
System.out.print(str);

19. Java String Replace(), ReplaceAll() &


ReplaceFirst() Methods
Java String replace() method is used to replace all the occurrences of any given
character with a new character.
String str = "CAT";

// Replaced the character 'C' with 'R'


String replace = str.replace('C', 'R');

// Printed the Original String


System.out.println("The Original String was: " + str);

// Printed the Final String after replace() operation


System.out.println("The Final String is: " + replace);

String str = "Shooting";

// Replaced the character sequence 'oot' with 'out'


String replace = str.replace("oot", "out");
// Printed the Original String
System.out.println("The Original String was: " +str);

// Printed the Final String after replace() char sequence operation


System.out.println("The Final String is: " +replace);

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";

/* * Replacing all the whitespaces between characters with the '%'*/


String replaceAll = str.replaceAll("\\s+", "%");

// Printed the Original String


System.out.println("Before ReplaceAll() " + str);

// Printed the Final String after replaceAll() operation


System.out.println("After ReplaceAll(): " + replaceAll);

Java String replaceFirst() method is used to replace the first occurring character with a
new character.
String str = "PPPPP";
System.out.println(str);

// Replaced the first occurrence of 'P' with 'Q'


String replaceFirst = str.replaceFirst("P", "Q");

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”.

public class replaceAll {


public static void main(String[] args) {

// 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");

// Printed the Original String


System.out.println("Before ReplaceAll() " + str);

// Printed the Final String after replaceAll() operation


System.out.println("After ReplaceAll(): " + replaceAll);

}
}
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.

public class replaceAll {


public static void main(String[] args) {

// 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);

// Printed the Final String after replaceAll() operation


System.out.println("After ReplaceAll(): " + replaceAll);

}
}
Output:

Scenario 3 –
String str = "Tony Stark John Jon StarkTony";

'$' means the last element of the matching pattern


So we have replaced the last occurrence of "Tony" with "Trevor" using regex =
"Tony$"

String replaceAll = str.replaceAll("Tony$", "Trevor");

// Printed the original element


System.out.println(str);

// Printed the replaced element


System.out.println(replaceAll);

What is a Wildcard Character? Explain.


A wildcard character is a special character that is used to represent any other character.
Any character can be used in the index where we have defined the wildcard character.
Some of the common wildcard characters are ‘*’, ‘?’ etc.

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.

20. Java String Contains() Method


This method is used to check whether a substring is a part of the main String. The return
type is Boolean.
This will return true if the invoking Object contains the String specified by the String variable
str. Otherwise, if it does not contains the String, it will return false.

String str = "Article on Java String contains";


System.out.println(str.contains("Java"));
//Java is a part of the main String str, so it will return true

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

Q #1) What happens when we pass a null value in the substring?


If we pass a null value in the substring, then it will throw “NullPointerException”.

Q #2) Can we use Java .contains() with StringBuffer?


Answer: Yes.
String str1 = "Java is a programming language";

StringBuffer stb = new StringBuffer("language");


System.out.println(str1.contains(stb));

Q #3) Can a String be null in Java?


Answer: Yes, a String can be null in Java.
There is a difference in the below two statements.
String str1 = "";

String str2 = null;

The first line is an empty String of length = 0.

The second line is a string variable with the null value or no value. There is no String
instance in this case.

Q #5) How do you ignore a case in Java?


Answer: In Java, we can either change the character case using toLowerCase() or
toUpperCase() method. Moreover, there are multiple methods that allow you to ignore the
case of a character. For Example, .equalsIgnoreCase(), .compareToIgnoreCase() and so
on.
String str1 = "SAKET";
String str2 = "saket";
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareToIgnoreCase(str2));

21. Java String CompareTo Method


The Java String compareTo() method is used to check whether two Strings are identical or not and finds
out if they are the same or which one is greater.

The return type of Java compareTo() method is an integer


int compareTo(String str) - str is a String variable that is being compared to the invoking
String.

int compareTo(Object obj) - we will compare a String with an Object obj

compareTo() Output Value Description

Zero Two Strings are equal.

Greater than Zero The invoking String is greater than str.

Less than Zero The invoking String is less than str.

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:

String str1 = "Software Testing";


String str2 = "Software Testing Help";

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:

String str1 = "SAKET";


String str2 = "saket";

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 = "";

System.out.println (str1.compareTo(str2)); //10


we have taken one String whose length we have to find and an empty String. Then we have
compared the String with the empty String. The difference between them will be the length
of the String.

22. What is the difference between


==, equals and .compareTo()?
!ERROR! unexpected operator '=' equals() compareTo()

!ERROR! unexpected operator '=' equals() is a method. compareTo() is a method.

!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.

String str1 = new String("Testing");


String str2 = "Testing";

System.out.println(str1.compareTo(str2)); // 0
System.out.println(str1 ==str2); // false
System.out.println(str1.equals(str2)); // true

23. How to read from XML or CSV file and store in


hashmap

24. Get the value of a cell in the Dynamic table


String sColValue = "Licensing";

//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)){

// If the sValue match with the description, it will


initiate one more inner loop for all the columns of 'i' row
for (int j=1;j<=2;j++){
String sRowValue=
driver.findElement(By.xpath(".//*[@id='post-2924']/div/table/tbody/
tr["+j+"]/td["+i+"]")).getText();
System.out.println(sRowValue);
}
break;
}
}

25. What is the Burndown chart (Agile)


A burndown chart is a tool used by Agile teams to gather information about both
the work they have completed on a project and the work that is yet to be done
within a given time period, or as Scrum teams call it, a Sprint.

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();
}

25. Explain Access specifiers


To ensure encapsulation and reusability, these access specifiers/modifiers are an integral
part of object-oriented programming. The access specifiers also determine which data
members (methods or fields) of a class can be accessed by other data members of classes
or packages etc.
#1) Access Modifiers - Access modifiers in Java allow us to set the scope or accessibility
or visibility of a data member be it a field, constructor, class, or method.

Access Inside Inside Outside package Outside


Specifier Class Package subclass package

Private Yes No No No

Default Yes Yes No No

Protected Yes Yes Yes No

Public Yes Yes Yes Yes

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();

// access the private variable using the getter and setter


d.setName("Java Programming");
System.out.println(d.getName());
}
}
Output:

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.

Q #2) Which Modifiers are not used for the class?


Answer: Protected and Private modifiers are not used for a class.

Q #5) what are Non-access Modifiers?


Answer: Modifiers that define the behavior of entities like class, method, or variables
with which they are associated are non-access modifiers. As the name suggests they do not
specify the access. Java provides various non-access modifiers like static, final,
synchronized, volatile, abstract, etc.
Java also provides non-access specifiers that are used with classes, variables, methods,
constructors, etc. The non-access specifiers/modifiers define the behavior of the entities to
the JVM.

26. Difference between Priority and Severity


Severity is “the degree of impact that a defect has on the development or operation of a
component or system.” Priority is “the level of (business) importance assigned to an item, e.g.,
defect.

Severity – Tester decides the severity of a defect.

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.

For instance, in a banking application, a user is unable to transfer money to any


beneficiary but that doesn’t affect their ability to add new beneficiaries.

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.

Priority – how quickly the defect needs to be fixed.

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.

Difference between Priority and Severity

SL.NO Severity Priority


Defined by the impact on the application’s
1. Defined by the impact on business.
functionality.
2. Category decided by testers. Category decided by developers or product owners.
Deals with the technical aspects of the
3. Deals with the timeframe or order to fix the defects.
application.
The value does not change with time, it’s Value of priority is subjective and may change after
4.
fixed. comparison with other defects.
1. High Severity and High Priority
Now, for example, the ‘Login’ button on the login form is not clickable. After filling in the login details,
the user is not able to click the ‘Login’ button and hence the user is not able to log in.
2. Low Severity vs. High Priority
On the user home page after login, banking application shows all the options of – Deposits, Transfer, and
Account Summary etc. In our example, the spelling of ‘Transfer’ is misspelt as ‘Transfer’. This error has
no effect on the functionality of the application because the user is able to click and perform a transfer
successfully. However, this is a drawback from the bank’s reputation perspective.

3. High Severity vs. Low Priority


For example, there are few actual users who are still using the older IE versions like IE8. The banking
application when accessed in older versions of IE, the page is not loaded completely and the form fields
are overlapped. This makes the accessibility of the website difficult for IE users using the older versions.
Hence, the severity is high because the whole application is impacted. However, there will be very few
actual users who will use IE 8 and other older versions, this makes the priority Low because this fix can
wait.

4. Low Severity vs. Low Priority


The ‘Help’ section of the banking website has a subsection, whose theme does not
match with the whole website. This defect is not hampering the website functionality,
also not many users will access this particular section. Hence, this defect falls under
the category of Low Severity and Low Priority.

Difference between Test Strategy and Test Scenario


27. What Software Metrics you have used in your
project?
Testing Metrics are broadly classified based on 2 objectives -

 Process Based Metric: Used to improve the processes involved in testing


 Product Based Metric: Used to measure the product quality, usability,
performance and provide a feedback on the defects detected.

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 ACCEPTANCE - Number of valid defects / Total number of defects identified.

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.

How to handle Dynamic Elements, since the webpage is


designed in Angular Js
28. Implicit and Explicit Waits
Implicit Wait Explicit Wait
 Implicit Wait time is
 Explicit Wait time is applied only to those
applied to all the
elements which are intended by us
elements in the script

 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

 It is recommended to  It is recommended to use when the elements are


use when the elements taking long time to load and also for verifying the
are located with the property of the element
time frame specified in like(visibilityOfElementLocated,
Selenium implicit wait elementToBeClickable,elementToBeSelected)

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.

1. Method overloading by changing data type of Arguments


void sum (int a, int b)
{
System.out.println(“sum is”+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println(“sum is”+(a+b));
}

cal.sum (8,5); //sum(int a, int b) is method is called.


cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.

2. Method overloading by changing no. of argument.

void find(int l, int b)


{
System.out.println(“Area is”+(l*b)) ;
}
void find(int l, int b,int h)
{
System.out.println(“Area is”+(l*b*h));
}
ar.find(8,5); //find(int l, int b) is method is called.
ar.find(4,6,2); //find(int l, int b,int h) is called.

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

30. Difference between super() and this() in java


Program
Sr. No. Key this super

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);
}

public B(int x, int y) {


super(x + 1, y + 1);// calls parent class constructor
this.x = x;
this.y = y;
}

public void print() {


System.out.println("Base class : {" + x + ", " + y + "}");
System.out.println("Super class : {" + super.x + ", " + super.y + "}");
}
}

class Point {
public static void main(String[] args) {
B obj = new B();
obj.print();
obj = new B(1, 2);
obj.print();
}
}
Output

Base class : {0, 0}


Super class : {1, 1}

Base class : {1, 2}


Super class : {2, 3}

31. What is Static Keyword


The static keyword is used for a constant variable or a method that is the same for every instance of a
class. The static keyword is a non-access modifier in Java that is applicable for the following:

Blocks, Variables, Methods, Classes

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.

// Java program to demonstrate use of static blocks


class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String[] args)


{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}

Static block initialized.


from main
Value of a : 10
Value of b : 40

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.

Important points for static variables: -


In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable
with scope limited to function), it violates the purpose of static. Hence, compiler does not allow static
local variable.
class Test {
public static void main(String args[]) {
System.out.println(fun());
}

static int fun(){


static int x= 10; //Error: Static local variables are not allowed
return x--;
}}

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:

 They can only directly call other static methods.


 They can only directly access static data.
 They cannot refer to this or super in any way.

// Java program to demonstrate restriction on static methods


class Test
{
// static variable
static int a = 10;

// 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 field b


b = 10; // compilation error

// 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"); }

public static void main(String[] args)


{ // main method}
}

When to use static variables and methods?


Use the static variable for the property that is common to all objects. For example, in class Student, all
students share the same college name. Use static methods for changing static variables.

// A java program to demonstrate use of


// static keyword with methods and variables

// Student class
class Student {
String name;
int rollNo;

// static variable
static String cllgName;

// static counter to set unique roll no


static int counter = 0;

public Student(String name)


{
this.name = name;

this.rollNo = setRollNo();
}

// getting unique rollNo


// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}

// 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);

// accessing static variable


System.out.println("cllgName : " + cllgName);
}}

// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");

Student s1 = new Student("Alice");


Student s2 = new Student("Bob");

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.

Remember: In static class, we can easily create objects.

Differences between Static and Non-static Nested Classes


The following are major differences between static nested classes and inner classes.

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.

// Java program to Demonstrate How to Implement Static and Non-static Classes


// Class 1 Helper class
class OuterClass {
// Input string
private static String msg = "GeeksForGeeks";

// Static nested class


public static class NestedStaticClass {

// 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);
} } }

// Class 2 Main class


class GFG {
// Main driver method
public static void main(String args[])
{
// Creating instance of nested Static class inside main() method
OuterClass.NestedStaticClass printer
= new OuterClass.NestedStaticClass();
// Calling non-static method of nested static class
printer.printMessage();

// 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();

// Calling non-static method of Inner class


inner.display();

// We can also combine above steps in one step to create instance of Inner class
OuterClass.InnerClass innerObject
= new OuterClass().new InnerClass();

// Similarly calling inner class defined method


innerObject.display();
}
}

Message from nested static class: GeeksForGeeks


Message from non-static nested class: GeeksForGeeks
Message from non-static nested class: GeeksForGeeks

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();
}

33. Read / Write code text file


import java.io.*;

class FileReader_example {

public static void main(String args[])throws IOException

FileReader fr=new FileReader("xyz.txt");

int p;

while((p=fr.read())!=-1)

System.out.println((char)i);

fr.close();

}
import java.io.*;

class Sample

public static void main(String args[])

try

FileWriter fw=new FileWriter("xyz.txt");

fw.write("hello how are you");

fw.close();

}catch(Exception e){ System.out.println(e);

System.out.println("congo...");

Select this value in the dropdown and hover to this element


and click
34. Assert and Verify
In the case of the “Assert” command, as soon as the validation fails the execution of that particular test
method is stopped. Following that the test method is marked as failed.

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(){

//Creating softAssert object


SoftAssert softAssert = new SoftAssert();

//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.

35. Check if a given string is Palindrome or not


// Main class
class GFG {

// Method 1 Returns true if string is a palindrome


static boolean isPalindrome(String str)
{
// Pointers pointing to the beginning and the end of the string
int i = 0, j = str.length() - 1;

// While there are characters to compare


while (i < j) {
// If there is a mismatch
if (str.charAt(i) != str.charAt(j))
return false;
// Increment first pointer and decrement the other
i++;
j--;
}
// Given string is a palindrome
return true;
}

// Main driver method


public static void main(String[] args)
{
String str = "geeks";
String str2 = "RACEcar";

//Change strings to lowercase


str = str.toLowerCase();
str2 = str2.toLowerCase();

// 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");
}
}

36. Remove duplicate characters from a string and


print
By using the simple for loop.

 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.*;

//Creating RemoveDuplicatesExample1 class


class RemoveDuplicatesExample1
{
//Creating removeDuplicates() method to remove duplicates from array
static void removeDuplicate(char str[], int length)
{
//Creating index variable to use it as index in the modified string
int index = 0;

// Traversing character array


for (int i = 0; i < length; i++)
{

// Check whether str[i] is present before or not


int j;
for (j = 0; j < i; j++)
{ if (str[i] == str[j])
{ break; } }
// If the character is not present before, add it to resulting string
if (j == i)
{ str[index++] = str[i]; }
}
System.out.println(String.valueOf(Arrays.copyOf(str, index)));
}

// main() method starts


public static void main(String[] args)
{
String info = "javaTpoint is the best learning website";
//Converting string to character array
char str[] = info.toCharArray();
//Calculating length of the character array
int len = str.length;
//Calling removeDuplicates() method to remove duplicate characters
removeDuplicate(str, len); } }

By using the sorting algorithm.

First, we need to sort the elements.


After that, we remove duplicates by comparing the current character with the previous character in a
loop.
In the end, we need to remove the extra characters at the end of the resultant string.

//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;

// index to track the location of next character(Resultant string)


int index2 = 1;

// Convert string to character array for further manipulation


char arr[] = str.toCharArray();

//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++;

str = new String(arr);


System.out.println(str.substring(0, index2));
}

//Create sortString() method to sort string


static String sortString(String str)
{
// Convert string to character array to sort it
char temp[] = str.toCharArray();

//sort array using array's sort () method


Arrays.sort(temp);

//Generate a new string from character array


str = new String(temp);

// Return the sorted string


return str;
}

// main() method start


public static void main(String[] args)
{
//create string variable with a default string
String str = "javaTpoint is the best learning site";

//Call sortString() method to sort the strign characters


String newString = sortString(str);
System.out.println(newString);

//Call removeDuplicates() method to remove duplicates from the sorted string


removeDuplicates(newString);
}
}

By using the hashing.

By using the indexOf() method.


Which Code Repository you are using (Ex: GitHub)
37. How will you estimate the time to automate a
scenario?
1. Complexity of the module.
2. Durability of the script adding (no. of try-catch block, Inputs from excel, etc)
3. UI
4. Dynamic elements
5. PopUp
6. Framework design
7. Experience
ROI = (Cumulative saving / Investment through automation)*100

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();

39. Different ways to convert int to String in java


1. Convert Integer to String using Integer.toString() method:
String str= Integer.toString(i);
 Integer is a wrapper class in java having some predefined methods to convert
integer value to string toString() (toString is a static method in Integer class so that by
using class name itself we can call that method to convert Integer to corresponding
string value.)

2. Convert Integer to String using String.valueOf() method.


int number=123;
String numberstr= String.valueOf(number);

Integer i = new Integer(64);


//converting integer to string by calling valueOf() method on String clas
String str= String.valueOf(i);

3. Convert Integer to String / int to String using new Integer(int).toString()


And here by creating Integer object and directly calling tostring method.
String numberstr= new Integer(number).toString();

4. Convert Integer to String / int to String using String.format() method


5. Convert Integer to String / int to String using DecimalFormat
6. Convert Integer to String/ int to String using StringBuffer / StringBuilder
7. Convert Integer to String / int to String directly by adding to ""
8. Convert Integer to String / int to String using Special radix.

40. In a Dynamic Table, if I give 1 cell value, it should


give me the values of other cells in that row
 Open Firefox browser
 Navigate to the demo site
 Locate ‘Books & Authors’ table using id
 Get the total number of rows using absolute XPath
 Get the total number of columns using relative XPath
 Print row and column count to console
 Get all row values by tag name ‘tr’
 Get the column header values in a list by tag name ‘th’
 Loop through the header values and print them to console
 Loop through the table contents (all columns for each row) and get its text
 Print the values to console
 Print the table contents to console using fixed row and column numbers
public class LoopingThroughTableElements {
// Declaring variables
private WebDriver driver;
private String baseUrl;

@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);

// Locate 'Books & Authors' table using id


WebElement BooksTable = driver.findElement(By.id("BooksAuthorsTable"));
//Get all web elements by tag name 'tr'
List<WebElement> rowVals = BooksTable.findElements(By.tagName("tr"));

//Get number of rows and columns


//using absoulute xpath
int rowNum =
driver.findElements(By.xpath("/html/body/form/div[5]/div/div/table/tbody/tr")).size();
//using relative xpath
int colNum =
driver.findElements(By.xpath("//table[@id='BooksAuthorsTable']/tbody/tr[1]/th")).size();
System.out.println("Total number of rows = " + rowNum);
System.out.println("Total number of columns = " + colNum);

//Get column header values from first row


List<WebElement> colHeader = rowVals.get(0).findElements(By.tagName("th"));
//Loop through the header values and print them to console
System.out.println("Header values:");
for(int i=0; i<colHeader.size(); i++){
System.out.println(colHeader.get(i).getText());
}
System.out.println("---------------");
//Loop through the remaining rows
for(int i=1; i<rowNum; i++){
//Get each row's column values by tag name
List<WebElement> colVals =
rowVals.get(i).findElements(By.tagName("td"));
//Loop through each column
for(int j=0; j<colNum; j++){
//Print the coulumn values to console
System.out.println(colVals.get(j).getText());
}
//Just a separator for each row
System.out.println("---------------");
}

//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.

xpath("//table[@id='BooksAuthorsTable']/tbody/tr[" + i +"]/td[" + j + "]")).getText() + "\t");


}
System.out.println("");
}

} //End of @Test

@After
public void tearDown() throws Exception {
// Close the Firefox browser
driver.close();
}
}

Have you Developed any Tool, If yes explain


41. Write code for handling Frames
The frame enables a developer to split the screen horizontally or vertically by using the frameset tag.
The iframes are mainly used to insert content from external sources. For example, an advertisement
displayed on a web page. They can float within the webpage, which means one can position an iframe at
a specific position on a web page.

It is possible to identify the iframes on a web page in two ways:

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

how to identify the total number of frames in a web page.

 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());

Switching Frames in Selenium using Index


driver.switchTo().frame(0);
driver.quit();

Switching Frames using Name or ID

driver.switchTo().frame("id"); // Switch By ID

Switching back to Main Page


The main page is where all the iframes are embedded. After operating on a particular iframe, use
switchTo().parentFrame to move back to the page page. Use switchTo().defaultContent to shift to the
primary/first parent frame.

driver.switchTo().defaultContent();

42. Read from a text file and store it in HashMap


De-Serialization: Here we are reproducing the HashMap object and it’s content from a
serialized file.
Approach:
Firstly, the method/Function HashMapFromTextFile will have the Method bufferedReader which read
the Line of the text File and insert into the map and then return the Map

bf = new BufferedWriter( new FileWriter(file_name) );

 Firstly, we call the BufferedReader to read each line.


 At each Line, We have the Key-Value Pair. So, now split it by “:” and same time put the key and
Value to the map
 and return the Map

// Java program to reading


// text file to HashMap

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();

// iterate over HashMap entries


for (Map.Entry<String, String> entry : mapFromFile.entrySet())
{
System.out.println(entry.getKey() + " : "+ entry.getValue());
}
}

public static Map<String, String> HashMapFromTextFile()


{
Map<String, String> map = new HashMap<String, String>();
BufferedReader br = null;
try {
// create file object
File file = new File(filePath);

// create BufferedReader object from the File


br = new BufferedReader(new FileReader(file));

String line = null;

// read file line by line


while ((line = br.readLine()) != null) {

// split the line by :


String[] parts = line.split(":");

// first part is name, second is number


String name = parts[0].trim();
String number = parts[1].trim();

// put name, number in HashMap if they are


// not empty
if (!name.equals("") && !number.equals(""))
map.put(name, number);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {

// Always close the BufferedReader


if (br != null) {
try {
br.close();
}
catch (Exception e) {
};
}
}

return map;
}
}

43. Print the occurrence of each character if it is


present more than once in a given string
import java.util.HashMap;

public class EachCharCountInString

private static void characterCount(String inputString)

//Creating a HashMap containing char as a key and occurrences as a value


HashMap<Character, Integer> charCountMap = new
HashMap<Character, Integer>();
//Converting given string to char array

char[] strArray = inputString.toCharArray();

//checking each char of strArray

for (char c : strArray)

if(charCountMap.containsKey(c))

//If char 'c' is present in charCountMap, incrementing it's count by 1

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);

//Printing inputString and charCountMap

System.out.println(inputString+" : "+charCountMap);

public static void main(String[] args)

characterCount("Java J2EE Java JSP J2EE");

characterCount("All Is Well");

characterCount("Done And Gone");

}
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

How will you generate Reports?


What is the execution time of your test cases?
Print a Reverse Pyramid
Go to frame and click on the upload button and select the
file which is in this directory
Difference between PUTS and POST in API
Read data from Excel and given that data as input for login
and password and click on submit and validate the popup
which says Login is successful
Read data from two text files and compare if they are the
same or not
Read data from an Excel file and compare the data to the
web table and check whether it is the same or not
Select multiple options from the dropdown
Explain Defect Lifecycle
How many people are working on your project, what all
teams are there
What is your role in your project?
How often Daily Triage Call will happen and what will be
discussed
What all packages you have used in your project
How will you check Broken Links?
Read from a text file and change that content
Write test scenario for Credit Cards
How to read Properties file
Which is the latest Java version and which one you have
used and what are the features of that version
Check if the given two strings are an anagram
What is the difference between Interface and Abstract
Methods?
Difference between BeforeSuite and BeforeMethod
Difference between Default and Protected
Write a program to divide without using division or modulus
symbol
String = ‘AaBbCcDD’ ,In that change a lowercase ‘a’ to
uppercase
Hierarchy of TestNg Annotations
How many Sprints you have worked on, how often you will
get Sprints
How Agile Methodology works
Do Exceptions have priority?
Can a try block have more than 1 catch block?
Can a class be Public, Private, Protected, and Default
How will you compare the data from the database to the
data on the webpage?
Blackbox vs Whitebox Testing
Explain Waterfall Methodology
What is Traceability Matrix
Explain STLC
Explain SDLC
What is a class
What is an object
What is a variable
How to clone one list and store it in a new list
How to run a group of test cases in TestNg
How to include or exclude test case in TestNg
How to run the parallel test case in TestNg
What is Selenium Grid
Can a Map have a Null value?
What all different test annotations you have used in TestNg
How to switch frame in Selenium
Difference between this and super
Difference between Constructor and Method
Difference between String Buffer and String Builder
Difference between List and Set
How to run a test suite in different browsers
What is static and final
Difference between String and String Builder
How to run failed test cases in TestNg
Difference between Iterator and ListIterator
How to set the proxy in Jenkins
Explain Maven Life Cycle
Explain POM
What will be there in POM.xml
Without using Select statement, how to select dropdown
Difference between Sanity and Smoke Testing
Can the Main Method be overridden?
What is Retrospective Meeting?
What all methods String has?
Get: Selenium Interview Questions

Selenium Tricky Automation Interview Questions

What are XPath and its types?


What are cross-browser testing and parallel testing?
Challenges faced during selenium testing?
What is the Actions class?
How to handle drop-down in selenium?
How to handle multiple browser pop up?
How to handle multiple browser tabs in selenium?
How to perform upload files using selenium?
How to perform download files using selenium?
How to get all values of dropdown in selenium?
How to perform (control + a) through selenium?
How to shift between tabs of the same browser using
selenium?
What is a Robot class?
What is AutoIT?
What is the difference between get() and navigate()?
What are the difference between findElement() and
findElements()?
What is difference between quit() and close()?
What are different locators used?
Difference between XPath and CSS selector?
Different approaches to click the submit button?
What is javascriptExecutor and when it is used?
Handling WebTable(static and dynamic) in selenium
What is POM? Advantage and its disadvantage?
What is a maven? list its phases or life cycle? Command to
run our project through the maven?
Explain ur project folder structure? Or Explain ur
framework?
What is TestNG?
How to create and delete cookies?
What does getwindowhandles() and getwindowhandle()
return? Or its differences?
Is it possible to use only perform() without build()? 30.What
is perform() and build()?
How to scroll the browser window?
Preceding sibling and following sibling of custom XPath?
What is the test management tool used in ur project?
What is the build automation tool used in ur project?
How u will handle the SSL certification?
What are DesiredCapabilities?
How to verify ‘Bangalore’ present in the dropdown box or
not?
How to verify ‘Bangalore’ present in 4×4 webtable? And
print the column and row number of it is present?
How to fetch the data from a particular row and column of
excel?
List all maven plugins like surefire plugin etc
What is Jenkins? And explain its use?
Explain the tags present in the testng.xml file
What is TDD?
What is BDD? Explain the cucumber framework? What are
gherkins?
What is Listener?
What is DataProvider?
What is parameterization?
What is PageFactory?
What is Apache POI API? Or how to read data from excel?
What are explicit and implicit waits?
What are the challenges faced in automation testing?
Write code for handling multiple browsers and switch to
new windows?
What is webdriver? And why webdriver is used?
List some selenium exceptions
What is StaleElementReferenceException?When this
occurs? And how to overcome such exceptions?
How do you group the test cases? And why?
How to include or exclude test cases?
What is NullPointerException?When it occurs?
What is a selenium grid?
Should have knowledge of all TestNG annotations.
How do you control the execution of your test cases/test
classes?
Git and its commands
Maven commands to execute, debug, compile
What is the current version of maven used?
How to identify broken links? How have done you in your
project? Write code or tell approach.
Write a code to fetch the value ‘Test’ from the excel sheet
which might be present in any cell in excel. Or check
whether the value ‘Test’ is present in excel or not.
How to pass values to textbox other than using sendKeys()?
How to click the login button other than using click(),
submit(), and JavascriptExecutor?
What is subversion?
Selenium Tricky Manual Interview Questions

What are test design techniques? Explain BVA and ECP


with some examples?
Explain STLC
Explain Bug Life Cycle
What is the difference between bug and defect?
What are severity and priority?
Explain SDLC
What are the differences between smoke and sanity testing?
Selenium Tricky Interview Questions For 5 Year Experienced Testers

Question asked in an interview in different organizations for 5 years of exp in last one
month.

Explain your current automation framework.


Current roles and responsibilities.
TestNg sequence.
Why no main method is required in TestNG execution.
How to connect to database.
Simple SQL queries on a group by and conditions.
SQL query to find the second highest salary without using a
subquery.
SQL query to sort the column in ascending.
SQL query to find duplicate using self-join.
What is the difference between HTTP and HTTPS?
Java program on finding duplicate characters.
Java program on bubble sort.
Excel utility to read excel using hashmap of hashmap.
What is dependency injection in cucumber and testng Both
and how we can achieve it?
Program to remove white space and replace it with a
comma.
Java program for taking input in ArrayList and returning in
an array.
What is thrust testing?
Write a creative test case for lift.
Write cucumber feature file using datatable.
What are the latest enhancements in selenium 4
How to pass parameters in Jenkins.
What is java generics and where you have used it in our
current automation framework?
Wap to take pass a get request using rest assured and from
response verify if data present in the database using SQL.
Difference between hashmap and linked hashmap
Different error codes.
What is the global variable in postman?
Environment variable in postman.
Difference between put and patch.
What is the 409 response code?
How to pass JSON file to a payload
Pass payload using a hashmap.
How to pass cookies in rest assured.
What is OUTH and why company use nowadays?
What is agile. Explain its different components. What is the
burndown chart?
Is velocity in agile.
How to resolve conflict in Git.
What is a pull request?
How to reverse ur code in git
Jenkins Cron’s job to set at every hour how.
By setting the schedule period to 15 13 * * * you tell Jenkins to schedule the build
every day of every month of every year at the 15th minute of the 13th hour of
the day.
Jenkins used a cron expression, and the different fields are:
1. MINUTES Minutes in one hour (0-59)
2. HOURS Hours in one day (0-23)
3. DAYMONTH Day in a month (1-31)
4. MONTH Month in a year (1-12)
5. DAYWEEK Day of the week (0-7) where 0 and 7 are sunday

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

Start by creating a new item.


Give your new item a name.
For this example, we’re using a Freestyle project, but the
scheduling configuration will be the same for all Jenkins jobs.

Click OK, and Jenkins will create your empty job.

Now, it’s time to give your job something to do. Click on


the Build tab on the configure page.
This will take you to the build section. Click on the Add build
step menu and select Execute shell.
We’re going to use a one-line shell step for this job.

Enter the single line of shell code and click Save.

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

Head back to the job configuration and click the Build


Triggers tab.

Now, check the Build periodically box in the Build Triggers


section.

This will open the scheduling text area.

Next, let’s set the job to run every five minutes.


Enter H/5 * * * * into the box, click Save, and reopen the
configuration. Jenkins will show you when the job will run.

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.

Here is a screenshot of a couple of builds on our system. You


can see that the first build corresponds to the time shown
above on the configure page.

The timestamps show that you’ve scheduled a job to run


every five 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;

public class TestListener implements ITestListener {

WebDriver driver=null;

String filePath = "D:\\SCREENSHOTS";

@Override

public void onTestFailure(ITestResult result) {

System.out.println("***** Error "+result.getName()+" test has failed *****");

String methodName=result.getName().toString().trim();

ITestContext context = result.getTestContext();

WebDriver driver = (WebDriver)context.getAttribute("driver");

takeScreenShot(methodName, driver);

public void takeScreenShot(String methodName, WebDriver driver) {


File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

//The below method will save the screen shot in d drive with test method name

try {

FileUtils.copyFile(scrFile, new File(filePath+methodName+".png"));

System.out.println("***Placed screen shot in "+filePath+" ***");

} catch (IOException e) {

e.printStackTrace();

public void onFinish(ITestContext context) {}

public void onTestStart(ITestResult result) { }

public void onTestSuccess(ITestResult result) { }

public void onTestSkipped(ITestResult result) { }

public void onTestFailedButWithinSuccessPercentage(ITestResult result) { }

public void onStart(ITestContext context) { }

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;

public class TestListener extends TestListenerAdapter {


WebDriver driver;
private static String fileSeperator = System.getProperty("file.separator");
@Override
public void onTestFailure(ITestResult result) {
System.out.println("***** Error " + result.getName() + " test has failed *****");

ITestContext context = result.getTestContext();


WebDriver driver = (WebDriver)context.getAttribute("driver");

String testClassName = getTestClassName(result.getInstanceName()).trim();

String testMethodName = result.getName().toString().trim();


String screenShotName = testMethodName + ".png";

if (driver != null) {
String imagePath = ".." + fileSeperator + "Screenshots"
+ fileSeperator + "Results" + fileSeperator + testClassName
+ fileSeperator
+ takeScreenShot(driver, screenShotName, testClassName);
System.out.println("Screenshot can be found : " + imagePath);
}
}

public static String takeScreenShot(WebDriver driver, String screenShotName, String testName) {


try {
File file = new File("Screenshots" + fileSeperator + "Results");
if (!file.exists()) {
System.out.println("File created " + file);
file.mkdir();
}

File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);


File targetFile = new File("Screenshots" + fileSeperator + "Results" + fileSeperator + testName,
screenShotName);
FileUtils.copyFile(screenshotFile, targetFile);
return screenShotName;
} catch (Exception e) {
System.out.println("An exception occured while taking screenshot " + e.getCause());
return null;
}
}

public String getTestClassName(String testName) {


String[] reqTestClassname = testName.split("\\.");
int i = reqTestClassname.length - 1;
System.out.println("Required Test Name : " + reqTestClassname[i]);
return reqTestClassname[i];
}
}
}

45. How to rerun failed TC 3 times.


Case 1: Execute failed test cases using TestNG in Selenium –
By using “testng-failed.xml”

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.

Case 2: Execute failed test cases using TestNG in Selenium –


By Implementing TestNG IRetryAnalyzer.
Create a class to implement IRetryAnalyzer. Here I am creating a class (say, RetryFailedTestCases) and
implementing IRetryAnalyzer.

package softwareTestingMaterial;

import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class RetryFailedTestCases implements IRetryAnalyzer {


private int retryCnt = 0;
//You could mentioned maxRetryCnt (Maximiun Retry Count) as per your requirement. Here I took
3, // If any failed testcases then it runs two times

private int maxRetryCnt = 2;

//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

public boolean retry(ITestResult result) {


if (retryCnt < maxRetryCnt) {
System.out.println("Retrying " + result.getName() + " again and the count is " + (retryCnt+1));
retryCnt++;
return true;
}
return false;
}
}
Let’s create another class ‘RetryListenerClass’ by Implementing ‘IAnnotationTransaformer’ interface.
transform method is called for every test during test run. A simple implementation of this
‘IAnnotationTransformer’ interface can help us set the ‘setRetryAnalyzer’ for ‘ITestAnnotation’. Add
the above class name (RetryFailedTestCases.class) in the below program. This interface does its work
in run time by adding annotation to the test methods.

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;

public class RetryListenerClass implements IAnnotationTransformer {

@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>

Final testng.xml file should looks like below:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="My Suite">

<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 -->

</suite> <!-- Suite -->

Testcase 1:
package softwareTestingMaterial;

import org.testng.Assert;
import org.testng.annotations.Test;

public class Test1 {

@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;

public class Test2 {


@Test
public void test2(){
System.out.println("Test 2");
Assert.assertTrue(false);
}
}

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
===============================================

What is the difference between drop and truncate in SQL?


46. What is alert in selenium?
An Alert in Selenium is a small message box which appears on screen to give the user some information
or notification like some specific information or error, asks for permission to perform certain tasks and it
also provides warning messages.

There are two types of alerts that we would be focusing on majorly:


1. Windows-based alert pop-ups

2. Web-based alert pop-ups

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.

This confirmation alert asks permission to do some type of operation.

How to handle Web-based alert pop-ups Alert in Selenium WebDriver

1) void dismiss() // To click on the ‘Cancel’ button of the alert.


driver.switchTo().alert().dismiss();
2) void accept() // To click on the ‘OK’ button of the alert.
driver.switchTo().alert().accept();

3) String getText() // To capture the alert message.


driver.switchTo().alert().getText();

4) void sendKeys(String stringToSend) // To send some data to alert box.


driver.switchTo().alert().sendKeys("Text");

How to handle Window-based alert pop-ups Alert in Selenium WebDriver

WebDriver Code using Robot Class


import java.awt.Robot;</pre>
import java.awt.event.KeyEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DemoWindowAlert {


WebDriver driver;
@Before

public void setUp()


{
driver=new FirefoxDriver();
driver.get("https://gmail.com");
driver.manage().window().maximize();
}

@Test
public void testWindowAlert() throws Exception{

// enter a valid email address


driver.findElement(By.id("Email")).sendKeys("TestSelenium1607@gmail.com");

// enter a valid password


driver.findElement(By.id("Passwd")).sendKeys("TestSelenium");

// click on sign in button


driver.findElement(By.id("signIn")).click();
Thread.sleep(30000);

// click on compose button


driver.findElement(By.xpath("//div[@class='z0']//
div[contains(text(),'COMPOSE')]")).click();

// click on attach files icon


driver.findElement(By.xpath("//div[contains(@command,'Files')]//
div[contains(@class,'aaA')]")).click();

// creating instance of Robot class (A java based utility)


Robot rb =new Robot();

// pressing keys with the help of keyPress and keyRelease events


rb.keyPress(KeyEvent.VK_D);
rb.keyRelease(KeyEvent.VK_D);
Thread.sleep(2000);

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);

We can easily switch to alert from the main window by using


Selenium’s .switchTo() method.
Have you used JavaScript executor in ur framework is yes
where?
Which framework is easy to handle data-driven, keyword-
driven, or hybrid.
Different design patterns we can use with selenium.
Can we integrate Sprint boot with selenium?
1. What is Jira? How your project maintains test case and
defect?

You can customize JIRA software for test management in either of the ways:
 Using the “User story”
 Adding a “Test Case” issue

1. Keep test cases simple and easy to understand.


2. Standardize naming conventions. - As business needs grow, scaling a test library can become a
challenge.

3. Describe detailed steps and include data

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.

2. What are the deliverables you deliver after the project


is done?
Test Deliverables In Software Testing

 Test strategy - Test manager or lead prepares a high-level document containing


Test objective, test approach, test scope, entry & exit criteria, types & levels of
testing, milestones, staffing, etc based on the Business requirement

 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.

 Reservation: Check the reservation functionality.


 Passenger details: Check the gender, age, and sex fields functionality.
 Modify: Check if the modify functionality works properly.
 Concession: Check if the concession functionality works properly.
 View: Check if the view functionality works properly.
 Cancel: Check if the cancel functionality works properly.
Here, the concession may be called as an “alternate scenario” as the user can book
with or without it based on the age. However, the goal is the same i.e. to book a
ticket.

 Test cases and test data


Thus, test cases tell what exactly needs to be tested in detail. Test cases have to be
written in simple language and should be easily understandable. It should be written
in proper format as asked by the concerned client.
Some project needs prior data from the client before proceeding with the execution
of the test case. Test data need to be applied to perform testing.

 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.

 Test summary report


All the test information such as members involved in testing, objectives, scope, client
details, test approach used, test results, defect report, etc are mentioned here.
However, the test summary report should be prepared as per the client’s advice.
Thus it a useful document for the client as well to review the overall performance.

 Test closure report


To close the project after testing and defect fixing. Therefore, we have to provide a
detailed analysis of the execution of the tests, defects found and fixes. The overall
requirement coverage is mentioned in this report. The team lead or manager
generally prepares it. All the exit criteria should be satisfied accordingly.

 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?

You might also like