0% found this document useful (0 votes)
62 views35 pages

Selenim Interview Questions (AutoRecovered)

Uploaded by

ashiqmohamed1907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views35 pages

Selenim Interview Questions (AutoRecovered)

Uploaded by

ashiqmohamed1907
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

// Launch the application

driver.get("http://demo.guru99.com/test/guru99home/");

//Different ways To maximize the window. This code may not work
with Selenium 3 jars. If script fails you can remove the line below

driver.manage().window().maximize(); OR

Dimension dimension = new Dimension(screen resolution size


1366,768); // Use of Dimension

driver.manage().window().SetSize(dimesion); OR

//Using Chromeoptions class – This will be add while initializing the


driver itself. After System.setProperty and before Webdriver driver

System.setProperty(“webdriver.chrome.driver”, “C:\\chromediver.exe
location”);
chromeOptions chromeoptions = new ChromeOptions();
chromeOptions.addArguments(“—-start-maximized”);
WebDriver driver = new ChromeDriver(ChromeOptions);

// Launch browser without System.setProperty()


Yes, we can launch browser without System.setProperty() . By adding driver path to the
Environment Variables and restart to take effect.

//Find element by link text and store in variable "Element"


WebElement Element = driver.findElement(By.linkText("Linux"))

// this will scroll down the page by 1000 pixel vertical


js.executeScript("window.scrollBy(0,1000)");

//How to handle authentication popup (username & Password popup)

We can’t use inspect & sendkeys instead,

We can send credentials via URL

hhtp://username:password@URL

driver.get("http://admin:[email protected]/test/guru99home/");

HOW TO CREATE XPATH GUIDE:

Inspect the webelement in a webpage

Move to the html code for the inspected element

Press Control + F – search field displayed

Xpath starts with // then html tag and add property then the name/class/id

After writing xpath, check whether its showing 1 0f 1 at the corner to use
Example 01: //input[@name=’username’] //If you’re using “@” then we have
to use =, if you’re using “contains” then use “,”

Example 02:
If no id/name/class is present then,
//input[@type=’submit’ and @value=’Login’] //[] attribute we
need to give inside, we can provide single or combination of multiple
attributes by using and operator

Example 03:

Xpath for links, If no property is present in the html tag like id/name/class/link, etc
//a[text()=’Winter’] //text() is a function so we cannot use ‘@’ here,
without contains

//a[contains(text),’Winter is coming’] //contains() is a function, so we


cannot use ‘@’ here, with contains we add the full sentence in xpath
– recommended then ‘text’ xpath

Example 04:

After writing xpath, if it’s showing 1 0f 2 at the corner then add


combination of multiple attributes using and operator

//button[@type=’button’ and @class=’btn’]

//button[contains(text),’sign up’]

Example 05:

Dropdown button having more than 1 class, and buttons having same property then xpath will
be included with parent type,
//div[@class=’dropdown’]//button[@type=’button’ and @class=’btn btn-
secondary dropdown-toggle’ and @id=’dropdownmenubutton1’] or

//button[@id=’dropdownmenubutton1’]

Example 06:

Xpath for checkbox in a table, if you’re using parent property in xpath use two colons “::”

CHILD -> PARENT -> PRECEEDING(reverse) SIBLING -> INPUT CHECKBOX


//a[text()=’test’]//parent::td[@class=’datalistrow]//preceeding-
sibling::td[@class=’datalistrow’]//input[@class=’contact_id’]

What is selenium webdriver?

It is the main component of selenium. Selenium webdriver has a collection of API’s (Class &
Interfaces) to automate the web application.

4 different components: Selenium IDE, RC, Grid & Webdriver

Selenium grid will distribute the automated tests across multiple machines.

Selenium grid used with testNG, can enable parallel execution of tests across multiple machines.

IN Selenium grid configuration, one machine is configured as Hub and other machines are
configured as Nodes. //*[@id="inPageSearchForm"]/div[2]/div/div/div[1]/div[4]/button

Automation tests are triggered for execution from Hub machine but the triggered test cases will
be executed in different node machines.
Node machines can have different platforms & browsers.

The total number of links in a page can be counted with the help of findElements() method.

List<WebElement> links = driver.findElements(By.tagName("a"));

To find no.of links = //a, it’ll show the count of total links …. //a means anchor tag to get all the links

How to count number of links in selenium?


List<Webelements> links = driver.findelements(By.tagName(“a”)); //a means
anchor tag to get all the links

Links.size(); // It’ll get the total count of links present in webpage

Action & Actions difference?


Action is an interface which represents a single user-interaction action. A variable of action
interface can be stored in action.
Act.movetoelement().build(); // Return type of build method is Action, it’ll return the action but not
perform
Action action = act.movetoelement().build();

Action.perform(); // build will create the action and perform method will complete the action

.perform() internally calling build().perform()

Actions is a Class, contains the different type of methods.

Actions class is an ability provided by Selenium for handling keyboard and mouse events. Action
class in derived from advanced user interactions API.

Mouse Actions in Selenium:

1. Actions.doubleClick(): Performs double click on the element


2. Actions.clickAndHold(): Performs long click on the mouse without releasing it
3. Actions.dragAndDrop(): Drags the element from one point and drops to another
4. Actions.moveToElement(): Shifts the mouse pointer to the center of the element
5. Actions.contextClick(): Performs a context-click at the current mouse location. (Right Click
Mouse Action)

Actions actions = new


Actions(driver);Actions.clickAndHold(Source”From”).moveToElement(Target”To”
).releaseTo(Target”To”).build().perform(); or

Actions.dragAndDrop(Source”From”, Target”To”).build().perform();

String toolTipText = name.getAttribute(“title”); // Tooltip can be


retrieved by “title” attribute
Javascript executor in selenium?

JavaScriptExecutor is an interface that is used to execute JavaScriprt through selenium webdriver.

JavaScriptExecutor provides two methods “executescript” & “executeAsyncScript” to run javascript


on the selected window or current page.

 executescript() method executes the test script in the context of the currently selected window
or frame. The script in the method runs as an anonymous function. If the script has a return
statement, the following values are returned:
 WebElement
 List
 String
 Long
 Boolean

Get Started with JavaScriptExecutor:


1. Import the package
Import org.openqa.selenium.JavascriptExecutor;
2. Create a reference
JavascriptExecutor js = (JavascriptExecutor) driver;
3. Call the JavascriptExecutor method
js.executeScript(script, args);

Using executescript() method we can do many actions in selenium,

Js.executeScript("window.location = 'URL'");// Navigate to page

executor.executeScript ("arguments[0].click();", button);// Perform Click


on LOGIN button

js.executeScript("window.scrollBy(0,600)");// //Vertical scroll down by 600


pixels

Js.executescript(“location.reload”);// To refresh page alternative way from


Get() & Navigate()

Gethandle & gethandles return string data type

driver.getWindowHandle() – It fetches the handle of the web page which is in focus. It gets the
address of the active browser and it has a return type of String.

driver.getWindowHandles(): It is used to get the address of all open browsers, and its return
data type is Set<String>.

webdriverManager.Chromedriver().setup();

webdriver driver = new chromedriver();

driver.get(“any web page”);


String Oldwindow = driver.getWindowHandle();//Getwindowhandle return type
is String

//Open browser and click any link to open child window

Set<String> handles = driver.getWindowHandles();// Set<String> Set – Is a


collection means more than

for(String newwindow : handles){ //for-each loop

driver.switchTo().window(newwindow);//Control will shift to new


window
} Webelement editbox = driver.findelement(By.xapth(“”));
Editbox.click();
driver.close(); //This will close the child window

driver.switchTo().window(oldwindow);// Control will shift to parent window

//Open multiple windows by clicking links from home page

Int numberofwindows = driver.getWindowHandles().size();// Size() method will


display the number of windows opened. Return type of Size is INT
Sys.out.print(“Number of windowsopened:” +numberofwindows);

//Close the child windows except parent window

for(String allwindows : handles){ //for-each loop


if(!allwindows.equals(oldwindow)){//allwindows not equal to oldwindow
driver.switchTo().allwindows();

driver.close(); } // This will close the active/the window which is


focused currently

} driver.quit();// This will close all the windows opened by the driver

How to handle Iframe in selenium webdriver?? Guru99.com

iframe is often used to add content from other sources like an advertisement into a web page. The
iframe is defined with the <iframe> tag. HTML document embedded inside another HTML
document.

Example: Ads popup or ads by any provider in the webpage

driver.switchTo().frame(0);// If a frame doesn’t have any ID or name means,


we can use index position starts with 0 and goes on.

Suppose if there are 100 frames in page, we can switch to frame by using index.

 driver.switchTo().frame(0);
 driver.switchTo().frame(1);

Nested Frame – HTML document embedded inside another HTML document which is embedded
into another HTML. Switching from Outer frame to inner frame.
driver.switchTo().defaultContent(); // Switching back to the main window
driver.switchTo().frame(1);// Frame 2
driver.switchTo().frame(“ID or Name or webelement”);// Directly mention ID
or name inside frame.

// prints the total number of frames

driver.switchTo().defaultContent();

List<Webelement> Totalframes = driver.findElements


(By.tagName("iframe")).size();// More than one webelements return List

Int size = Totalframes.size(); // Size will return Int

How to perform right click in selenium?

Right click action in Selenium web driver can be done using Actions class. Right Click operation is also
called Context Click in Selenium. Pre-defined method context click provided by Actions class is used
to perform right click operation. (Right Click Mouse Action)

Actions actions = new Actions(driver);


WebElement element = driver.findElement(By.id("ID"));
actions.contextClick(element).perform();

Double click action in Selenium web driver can be done using Actions class. Actions class is a
predefined class in Selenium web driver used to perform multiple keyboard and mouse operations
such as Right Click, Drag and Drop, etc.

Actions actions = new Actions(driver);


WebElement element = driver.findElement(By.id("ID"));
actions.doubleClick(element).perform();

Double click & Alert

driver.get("http://demo.guru99.com/test/simple_context_menu.html");
driver.manage().window().maximize();

//Double click the button to launch an alertbox


Actions action = new Actions(driver);
WebElement link =driver.findElement(By.xpath("//button[text()='Double-Click
Me To See Alert']"));
action.doubleClick(link).perform();

//Switch to the alert box and click on OK button


Alert alert = driver.switchTo().alert();
System.out.println("Alert Text\n" +alert.getText());
alert.accept();

TestNG suite?
TestNG data provider? Watch video with example

How to do parallel testing using TestNG – VERY VERY VERY IMPORTANT


Listerners apply in different ways?
How will you connect database?
Pagefactory video?
Automation challenges?

How will you perform dropdown in selenium? Syntax and methods you need to explain

Using Select Class

WebElement dropdown1 = driver.findElement(By.id("ID"));


Select select = new Select(dropdown1);
//dropdown will have select tag, Select
is a class
Select.selectbyindex(0); //we can use any option to select from
dropd down (Index, value or visible text)

//to get the number of drop down options

List<WebElements> dropdownOptions = Select.getOptions(); // One or


more options means collection type we use, List
Int size = dropdownOptions.size(); // Size will get the number of
options available, Sixe return type is INT

//we can use sendkeys also to select from drop down options

dropdown1.sendkeys(“dropdown option”);

//we can also do multi-select from drop down options

Select multiselect = new Select(multiselect);


multiselect.selectbyindex(0);
multiselect.selectbyindex(1);
multiselect.selectbyindex(2);

Maven project, POM.xml - Lifecycle


Maven clean & Test
Maven setting.xml watch video
How to handle Browser cookies in selenium?
What is Maven surefire plugin?
Jenkins integration
TestNG grouping example – Regression and Smoke Testing
Compile time polymorphism & runtime polymorphism

 Throw: Throw keyword is used to throw exception to the runtime to handle it.
 Try/Catch: A @try block encloses code that can potentially throw an exception. A @catch()
block contains exception-handling logic for exceptions thrown in a @try block.
 Finally Keyword always used with Try Catch block, Finally block will get executed after the
Try Catch block.
 Finally: A @finally block contains code that must be executed whether an exception is
thrown or not:
 The finally block is always executed, even if the try block or catch block contains a return
statement.
 Finalize keyword used to perform the cleanup. Using garbagecollector().
 Final keyword (f-small) used to define the constant value, value we cannot change/modify
the value of final variable. It also used to prevent inheritance.
 The finalize() method in Java is called when an object is about to be garbage collected. The
finalize() method can be used to perform any necessary cleanup before the object is garbage
collected.

HTTPS STATUS CODE:

A server generates HTTP Status codes in response to the request submitted by the client to the
server. The first digit of the status-code is the response type, and the last two digits have
different interpretations associated with the status code.

 200 – Valid Link/success


 301/302 - Page redirection temporary/permanent
 404 – Page not found
 400 – Bad request
 401 – Unauthorized
 500 – Internal Server Error

Difference between webdrivermanager & webdriver?

WebDriverManager: WebDriverManager.chromedriver().setup();It will


automatically downloads the Driver Executable/s. WebdriverManager is an open source.

1. It checks the version of the browser installed in your machine (e.g. Chrome, Firefox).
2. It checks the version of the driver (e.g. chromedriver, geckodriver). If unknown, it uses the
latest version of the driver.
3. Check if the driver is already present in our system. If yes, does nothing. If not, it downloads
and set the environmental path.
4. To use WebdriverManager in Maven project, we need to add dependency in pom.xml
WebDriverManager is an open source not part of Selenium WebDriver API.

Webdriver: System.setProperty("webdriver.chrome.driver",
"./Drivers/chromedriver.exe"); This will setup driver executable for a specific
browser based on the location that we have provided where we downloaded and placed
driver executable/s.

To automate web applications we need to download driver executables manually for required
browsers. Once driver executables are downloaded into local system then we need place them in a
specific path and set path for driver executables

1. We need to download driver executables manually and set path for the same.

2. As and when browser version is updated, we need to download driver executable/s that can be
matched with latest browser version.

3. We need to set exact path for driver executable/s else we get illegalStateException. [When we try
to launch browser without setting correct path for driver executable/s]

How do you call a static variable outside a class?


Inside of a class, you can refer to its static variables simply by using their names. But
to access them from another class, you need to write the name of the class before
the name of the static variable. The variable is private . It is not visible outside the
class.

Which listener interface is used to re execute the failed test cases?


To rerun failed test runs automatically during the test run itself, we
implement IRetryAnalyzer interface provided by TestNG. By overriding retry()
method of the interface in your class, you can control the number of attempts to
rerun a failed test case.

To rerun failed test runs automatically during the test run itself, we
implement IRetryAnalyzer interface provided by TestNG. By
overriding retry() method of the interface in your class, you can control
the number of attempts to rerun a failed test case. s
public class RetryAnalyzer implements IRetryAnalyzer {

//Counter to keep track of retry attempts


int retryAttemptsCounter = 0;

//The max limit to retry running of failed test cases


//Set the value to the number of times we want to retry
int maxRetryLimit = 3;

//Method to attempt retries for failure tests


public boolean retry(ITestResult result) {
if (!result.isSuccess()) {
if(retryAttemptsCounter < maxRetryLimit){
retryAttemptsCounter++;
return true;
}
}
return false;
}

 Now add an attribute called “retryAnalyzer” to @Test annotated


method with value as Implemented class name as shown below

package testngDemo;
import org.testng.Assert;
import org.testng.annotations.Test;
public class RerunFailedTest1 {
int counter;

@Test
public void test1() {
System.out.println("test run");
Assert.assertTrue(true);
}
@Test(retryAnalyzer = RetryAnalyzer.class)
public void failedtest1() {

System.out.println("Failed test run");


Assert.assertTrue(false);
}
}

1. How many types of web drivers API’s are available in Selenium?

Chrome driver, Firefox Driver, Internet Explorer driver, HTML Unit Driver, Android driver,
Iphone driver, Remote web driver.

2. How to make sure page is loaded in selenium using web driver?

Selenium.iselementpresent(“Mention element Xpath”); this would check whether the


element is there or not.

Page to load – Add condition like selenium.waitforpagetoload(write the time here)

3. How can we launch a batch file in selenium webdriver project?

Using Process batch file run command.

First take the path of batch file, process batch = runtime.getruntime(“batch file path”);

4. How do you run selenium webdriver from command prompt/line?

To achieve that we can write java -classpath selenium-server- (standalone) Jar file (which we
get after download selenium) class name and hit enter
5. What are the different exceptions you face in selenium webdriver?

Totally 5 exceptions there,

No alert present exception - it means that the test is too quick and is trying to find an alert
that has not yet been opened by the browser.

To handle or simply avoid this exception, use explicit or fluent wait in all events where an
alert is expected.

No such window exception - NoSuchWindowException occurs if the current list of windows


is not updated. The previous window does not exist, and you can’t switch to it.

No such element exception - the exception occurs due to the use of incorrect element
locators in the findElement(By, by) method.

To handle this exception, use the wait command. Use Try/Catch to ensure that the program
flow is interrupted if the wait command doesn’t help.

Timeout exception - This exception is thrown if the command did not execute or complete
within wait time. As already mentioned, waits are used to avoid NoSuchElementException.

Element Not Visible Exception - When the WebDriver tries to find an element that is hidden
or invisible. To handle this exception, it is essential that the exact reason is identified, which
can be due to nested web elements or overlapping web elements.

In the first case, you have to locate and correct the specific element. In the second case, use
explicit wait.

6. What you mean by timeout exception?

It is related to a timing, whenever a command performing an operation does not complete


in an expected amount of time duration.

7. What is no such element exception?

When an element with given attributes is not found on the webpage.

8. What is stale element exception? (Very important question)

When the element is present in the DOM (Document object model) but it is not visible on
the webpage. EX: Train ticket availability number refresh (Using ajax call), you can try to
access the element several times in a loop before finally throwing an exception.

9. Page object model?

Is a design pattern in selenium creating an object repository for storing all web UI element.

In Page Object Model, consider each web page of an application as a class file. Each class file
will contain only corresponding web page elements. Using these elements, testers can
perform operations on the website under test.

10. How to scroll down to a page using java script in selenium?

Window.scrollby(0, document.body.scrollheight) to scroll down to a bottom of a page

Java function to scroll to top of web page: window.scrollTo(0,0)


Java function to scrollup: window.scrollby(x,y) or .scroll(x,y) // X is always 0 for scroll down

Java function to scrollup: Window.scroll(x,-y) // X- Horizontal, Y – Vertical, -y: will go up

//Scroll down till the bottom of the page


js.executeScript("window.scrollBy(0,document.body.scrollHeight)");

To scroll down to particular element use,


//This will scroll the page till the element is found
executor.executeScript("arguments[0].scrollIntoView();", Element);

//This will scroll the web page till end.


executor.executeScript("window.scrollTo(0,
document.body.scrollHeight)");

scrollIntoView();", Element); used for horizontal and Vertical


scroll page until the mentioned element is visible on the current
page.
Robot.Keypress(KeyEvent.Page_down)
Robot.KeyRelease(KeyEvent.Page_down)
Robot.Keypress(KeyEvent.Page_up)
Robot.KeyRelease(KeyEvent.Page_up)

11. Which all file types can be used as a data source for different frameworks?

Property files can used for different frameworks

.csv – Is one of the property files that we can use in selenium framework

Other file extensions like, excel, xml, text file

12. What are the listeners in selenium?

It is defined as an interface that modifies the behavior of the system. Listeners allow
customization of reports and logs.

2 types of listeners, webdriver & TestNG listeners.

Without using sendKeys() command entering text into


text fields – Using Javascript Executor

Get an attribute value of an element using Selenium


WebDriver
- Using Getattribute() command to retrieve the value displayed in the web page
- Return type is string for getattribute() command

How to press Enter key using Selenium WebDriver?


- Passing keys.Enter inside Sendkeys command
How does it work with pagination logic in java ?

4. Important: One parent window multiple child windows are opened to switch to
child windows (2) second one there is no title of the page?

13. Is it possible to navigate back & forth in webpage in a selenium? Which methos is used?

driver.manage.naviagte()

driver.manage.forward()

driver.manage.back()

driver.manage.navigate(“url”)

14. How to take screenshot in selenium webdriver?

We can use Takescreenshot interface for that.

Using Getscrenshotas method we can save the screenshot.

Convert web driver object to TakeScreenshot

CODE TO TAKE BASIC SCREENSHOT:


TakesScreenshot scrShot =(TakesScreenshot)webdriver;
File sourcefile = Screenshot.getscreenshotas(Outputfile.File);
File destinationfile = new file (“D://sample.png”);
FileHandler.copy(Sourcefile, destinationfile);// This is save the image in
local

Take screenshot when an alert is open, It’ll give you exception “selenium.UnhandledAlertException”

USING ROBOT CLASS AS WELL WE CAN TAKE SCREENSHOT

Call getScreenshotAs method to create image file


File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);

CODE TO TAKE FULL SCREENSHOT: (Not possible using Takesscreenshot)

Fullscreen shot possible using Robot Class

Robot robot = new Robot(); //Robot is a Java AWT

Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();//


Dimension is a data type for last used method “.getScreensize”

Rectangle rectangle = new Rectangle(Screensize); // Rectangle is a Java AWT

BufferedImage Source = Robot.CreateScreenCapture(rectangle); // BufferedImage


is a data type for last used method
File destinationfile = new file (“D://robotpic.png”);
ImageIO.write(source,”png”, destinationfile); // ImageIO class will take the file
from source to destination location

15. Testing types commonly achieved using selenium?


Smoke Testing

Integration Testing

System Testing

End-to-End Testing

Regression Testing

Compatibility Testing

Performance Testing

UI/UX Testing

16. What do you mean by assertion in selenium? (Very Important Question)

Asserts are validations or checkpoints for an application. Assertions state confidently that
application behaviour is working as expected. Asserts in Selenium validate the automated
test cases that help testers understand if tests have passed or failed.

It is a verification point. Types of assertion,

Assert: Assert command checks whether the given condition is true or false. Let’s say we
assert whether the given element is present on the web page or not. If the condition is true
then the program control will execute the next test step but if the condition is false, the
execution would stop and no further test would be executed.

Verify: Verify command also checks whether the given condition is true or false. Irrespective
of the condition being true or false, the program execution doesn’t halts i.e. any failure
during verification would not stop the execution and all the test steps would be executed.
Waitfor: This command waits for some condition to become true. They will fail and halt the
test if the condition does not become true within the current timeout setting. Perhaps, they
will succeed immediately if the condition is already true.

Hard Assertions are ones in which test execution is aborted if the test does not meet the
assertion condition. The test case is marked as failed. In case of an assertion error, it will
throw the “java.lang.AssertionError” exception.
Different types of hard assertions with examples.
assertEquals() is a method that takes a minimum of 2 arguments and compares actual
results with expected results. If both match, the assertion is passed, and the test case is
marked as passed. assertEquals() can compare Strings, Integers, Doubles, and many more
variables.

assertNotEquals() is a method that does the opposite of the assertEquals() method. In this
case, the method compares the actual and expected result. But if the assertion condition is
met if the two are not identical. The test case is marked as passed if actual and expected
results are not the same.

assertTrue(): This Assertion verifies the Boolean value returned by the condition. If the
Boolean value is true, then the assertion passes the test case.
assertFalse(): This method works the opposite of assertTrue(). The Assertion verifies the
Boolean value returned by the condition. If the Boolean value is false, the assertion passes
the test case.

assertNull(): This method verifies if the expected output is null. If not, the value returned is
false.

assertNotNull(): This method works opposite to the assertNull() method. The assertion
condition is met when the method validates the expected output to be not null.

17. What are the different build phases in Maven?


6 Build phases in Maven.
Validate
Compile
Test
Package
Install &
Deploy

SenthamilSelvan (11+Years)_System Engineer

18. How will you handle mouse and keyboard actions using selenium?

Using Action class.

Actions class is an ability provided by Selenium for handling keyboard and mouse events. Action
class in derived from advanced user interactions API.

Mouse Actions in Selenium:

6. doubleClick(): Performs double click on the element


7. clickAndHold(): Performs long click on the mouse without releasing it
8. dragAndDrop(): Drags the element from one point and drops to another
9. moveToElement(): Shifts the mouse pointer to the center of the element
10. contextClick(): Performs right-click on the mouse

Keyboard Actions in Selenium:

1. sendKeys(): Sends a series of keys to the element


2. keyUp(): Performs key release
3. keyDown(): Performs keypress without release
4. Ways to press enter key to perform Google search –
searchbox.sendkeys(“Searchterm”+keys.ENTER);
OR Searchbox.sendkeys(“search term”); // Use sendkeys(“searchterm \n”);
Searchbox.submit(); OR
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER)
robot.keyRelease(KeyEvent.VK_ENTER)

Robot class for keyboard and mouse actions:

 keyPress(): Example: robot.keyPress(KeyEvent.VK_DOWN) : This method with press down


arrow key of Keyboard
 mousePress() : Example : robot.mousePress(InputEvent.BUTTON3_DOWN_MASK) : This
method will press the right click of your mouse.
 mouseMove() : Example: robot.mouseMove(point.getX(), point.getY()) : This will move
mouse pointer to the specified X and Y coordinates.
 keyRelease() : Example: robot.keyRelease(KeyEvent.VK_DOWN) : This method with release
down arrow key of Keyboard
 mouseRelease() : Example: robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK) : This
method will release the right click of your mouse

19. To Open browser alternate command:

WebDriverManager .ChromeDriver().setup();

WebDriver driver = new Chromedriver();

20. Difference between Get() method & navigate.to() method?


Get & navigate.to methods, both methods are used for opening URL in the browser.

Only difference can be found in the parameters.

Get() accepts only one string parameter

Navigate.to() accepts string parameter and URL instance as parameter.

21. Implicit Wait – Is a global wait which waits for all the webelements equally.
It’s a dynamic wait because its only wait if its required.
Driver.manage().timeouts.implicitlywait(30, Timeunits.seconds); //Default waiting time is 0
second
22. Explicit Wait – Used to wait for a specific web element to be displayed or loaded

Webdriverwait wait = new webdriverwait(driver,5);

Wait.until(Expected Conditions.visibilityofelementloacted(by.id())); // Element to be visible

Wait.until(Expected Conditions.elementstobeclickable(by.id())); //Element to be clickable

23. Fluent wait – FluentWait instance defines the maximum amount of time to wait
for a condition, as well as the frequency with which to check the condition.
User also configure the wait to ignore specific types of exceptions while
waiting, such as NoSuchElementExceptions when searching for an element
on the page.

Default polling time is 0.5second. polling is nothing but frequency (3secs)

PAGE OBJECT MODEL (POM)

Is a design pattern in selenium creating an object repository for storing all web UI element.

In Page Object Model, consider each web page of an application as a class file. Each class file will
contain only corresponding web page elements

Object Repository means collection of all the web objects or web elements.

Page object model framework, same has been used for UI automation, API automation & Mobile
automation.

HOW TO EXPLAIN AUTOMQATION FRAMEWORK

Programming Language: Java

POM: As per page object model, we have maintained a class for every web page. Each web page has
a separate class and that class holds the functionality and members of the web page. Separate
classes for each individual test.

Packages: We have separate packages for pages and tests. All the web page related classes come
under the pages package and all the tests related classes come under the Tests package.

For ex: Login page and Payment page have separate classes to store element locators.

Property Files: This file (cofig.properties) stores the information that remains static throughout the
framework such as browser specific information, application url, development, testing url
screenshots path, security questions & answers, username, password, etc

TESTNG: Using TestNG for Assertions, grouping and parallel execution

Screenshots: Screenshots will be captured and stored in a separate folder and also the
screenshots of failed test cases will be added to the extent reports.

Maven: Using Maven to create a build, execution and dependency purpose. Integrating the
TestNG dependency in POM.xml file and running this POM.xml using Jenkins.

Version Control Tool: We use GIT as a repository to store our test scripts.

Jenkins – CI to trigger the build, we execute test cases on a daily basis based on the schedule. Test
results will be sent to peers using Jenkins.

Jenkins using POM.xml configuration, we integrated with devops. We’ll give the pom.xml file
location to devops.

Whenever the build is run it’ll automatically execute the test scripts.
Test Base Class: TestBase.java deals with all the common functions used by all the pages. This class is
responsible for loading the configurations from properties files, initializing the webdriver, implicy
waits, Extent reports.

We’ll push the code to BigBucket

From GIT use PULL to get the latest code from Master branch

Java to write the code

Selenium Webdriver

TestNG for writing test cases

Maven to create a build

Apache POI API to read the data from excel file

TestNG report

Jenkins – CI to trigger the build

GIT – Repository to maintain the code to push the code for check-in/check-out

Easy maintenance

Test Cases -> Extract -> How to find

How to find webelement without using Findelement?

Yes, using page factory @findby annotations above the particular element. Or We can directly use
the name/ID as a variable name in webdriver.

To include webdriver in selenium using “initelements” method,

Pagefactory.initElements(driver, LoginPageObjects.class); // include driver & class name of test

Webdriver Variable name (q).sendkeys(‘’searchterm”);

Get() is used to navigate to particular url (website) and wait for page load.

Navigate.to() is used to navigate to particular url (website) and does not wait to page load. It
maintains browser history or cookies to navigate back or forward.

How Selenium Testing is Integral to Continuous Integration/Delivery (CI/CD)


What is CI/CD?
Continuous Integration/Delivery prioritizes delivery of new releases of a build, frequently and
quickly. A project that’s launched remains open to continuous iterations (like Agile).
The only difference is this: the project also remains ready to be shipped at all times (instead of
waiting for iterations to run their course).

A broken link, often called a dead link, is any link on a web page that no longer works because there
is an underlying issue with the link. When someone clicks on such a link, sometimes an error
message is displayed like a page not found. There may not be any error message at all. These are
essentially invalid HTTP requests and have 4xx and 5xx status code. Some common reasons for a
broken link on a webpage can be:

 The destination web page is down, moved, or no longer exists.


 A web page moved without adding a redirect link.
 The user entered an improper/misspell URL.
 The web page link removed from the website.
 With activated firewall settings, also the browser cannot access the
destination web page at times.

Worked on Framework enhancements

Test scripts developed based on the functionality, Worked on the functional scripts.

For the past the 6months I’m working on the management activities

Jenkins using Palm configuration, we integrated with devops. Whenever the build is run it’ll
automatically execute the test scripts.

We’ll give the palm file location to devops.

RD Automation Channel

Page object model framework, same has been used for UI automation, API automation & Mobile
automation.

Mainly worked on web automation.

GIT – Eclipse ide used for GIT. Git add tat will mov to stage/index then GIT commit, this will be stored
in local repository, then GIT push will move to GIT cloud.

Code repository maintain in bitdocket,

Excel read & write

Fluent wait – default polling time is 0.5second. polling is nothing but frequency (3secs)
Full page A-shot – important

Java exception handling – Important

Exception – Is an undesirable or unexpected event, which occurs during execution of a program.

Exception is not an error. It can be handled in programs.

Two Types of exception – Checked & Unchecked exception.

Checked Exception – Occur during the compile time itself (while writing program itself (Red line)).

Un-Checked Exception – Run time exception (Null pointer exception)

Try Block – Code is written in this block which may give run time exception. Try block can have
multiple Catch block.

Catch Block – This is where the exceptions are handled. Catch block is immediately followed by Try
block. If there are no exceptions then the Catch block will not get executed.

Finally Block – Code will get executed even if the exception occurs or not. This block will contains
codes like closing connection of DB’s, buffers, streams, etc.

There is no finally block without a Try-Catch. A finally block must be associated with a try catch.

Finally block is not mandatory. If there’s any exception, then finally block will get executed after the
corresponding Catch block, else after Try block execution.

Finally block can also have exception. It can be handled using Try-Catch block.

Finally block will execute even after Return/Break/Continue statement.

Finally block will not get executed under below conditions,

 Thread is dead
 When System.exit() is called
 When an unrecoverable exception happens in finally block.

How to handle pagination elements using selenium

 First identify the pagination footer and get the size of it. If the size is greater than zero, then
we have pagination, else there’s no pagination.
 We’re going to get the list of names from the web page table and add it to the list. So we
need two lists, one is string type and another one is webelement type List<String> nameList;
and List<WebElement> listOfNames;
 Elements to be found,
 Pagination footer
 We need to click Next button, so next button
 Table data
 Logic going to use,
 Going to find size of pagination, if zero perform logic to click next button and fetch
name else do nothing.
 Find name cells and store in list of webelements
 Create a for-each loop, iterate and store the names in list of string
 Find next button/link
 At the end of page, next button will be disabled so we are going to use that as our
indicator for end of the pagination.

webdriverManager.Chromedriver().setup();

webdriver driver = new chromedriver();

driver.get(“any web page”);

List<String> nameList = new ArrayList<String>();

List<WebElements> listofNames;

Int sizeOfPagination = driver.findelements(By.xapth”Pagination Xpath using anchor tag //a+ size of


it”.size()); // size will give the integer value so I’ll save this in INT Variable

If(sizeofpagination>0)

Do{ // This next button is click under do-while loop

ListOfNames = Driver.findelements(By.xpath(“Table xpath in sort order”));

For (Webelement name: ListofNames){

Nameslist.add(name.gettext());

Nextbutton = driver.findelement(“Nextbutton xpath”);

Nextclassname = nextbutton.getattribute(class);

If(!nextClassName.contains(“disabled”)){ // !NextClass Name – Nextbutton class not contain


disabled

Nextbutton.click();

} else {

Break; }

While(true);

} else {sys.out.println(No pagination in this page);

MUST KNOWN JAVA CONCEPTS

1. OOPS concepts and how you used in your project


2. How will you achieve multiple inheritance?

Java supports multiple inheritance using interfaces not classes.

When the child class extends from more than one superclass, it is known as multiple inheritance.
However, Java does not support multiple inheritance.

To achieve multiple inheritance in Java, we must use the interface.

3. Difference between Interface & abstracts?

4. Difference between Array & Array list?

Array list:

ArrayList will maintain insertion order

ArrayList will allow duplicate element

To get index value use arraylist.get(1);

To get index position use arraylist.indexof(“Value”);// Index of will show the first occurrence in
code

To get index last position use arraylist.lastindexof(“Value”);// LastIndex of will show the last
occurrence in code

If element not present in the arraylist, it will return -1

To copy one collection to another collection in arraylist, arraylist.addall(which list to add); // .clear()
will clear the list

To remove use arraylist.remove( Using Index position/Value);

NULL insertion is possible, arraylist.add(null);

To update the element in particular position, arraylist.set( index value, value);

Using Listiterator we can go in forward & reverse direction

Listiterator.hasNext()

Listiterator.previous()

But in Iterator only forward possible, Iterator.hasNext()

Concurrent Modification Exception – If an arraylist performing any iteration and trying to


add/modify inside the Iteration means, exception will display.

Arraylist –Synchronized is no and thread also not possible

Copyonwritearraylist allows us to modify the list while reading it.

5. This keyword & Super Keyword

6. Types of exceptions in Java

7. Exceptions handling in Java


8. Difference between Hash map & Hash table?

9. Difference between collection & collections?

10. Difference between String, String builder & String buffer?

String is immutable and String buffer is mutable. Both are child of CharSequence interface.

String buffer is synchronized i.e. multiple threads cannot access it.

Can able to create object using New Keyword only for String Buffer.

String builder is mutable. Both are child of CharSequence interface.

String buffer is Non-synchronized i.e. multiple threads can access it simultenaously.

String buffer is less efficient less than String builder.

11. Constructors types

12. Difference between Final, finalize & finally?

Final is an access modifier, finally is the block in Exception Handling and finalize is the
method of object class.

Final: Final keyword and access modifier used to define the constant value. We cannot modify the
value of final variable. It used to prevent inheritance. Final class/Final method

Finalize: Finalize (Garbage Collector) is the method in Java which is used to perform clean up
processing just before destroying any object. If there’s no object reference is available, immediately
garbage collector will be called or automatically it’ll be called. Get SYNTAX for this

Finally: Is a block, finally block will be executed after try catch block despite of exceptions. Any
exceptions is coming or not, Finally block will get executed.

Finally is the block in Java Exception Handling to execute the important code
whether the exception occurs or not.

Include Catch block (NullPointerException), after arithmetic exception, exception will not catch it
because of null pointer, even then Fianally block will get execute.

Sr. Key final Finally finalize


no.

1. Definition final is the keyword and access finally is the block in Java Exception finalize is the method in Java which
modifier which is used to apply Handling to execute the important is used to perform clean up
restrictions on a class, method or code whether the exception occurs processing just before object is
variable. or not. garbage collected.

2. Applicable Final keyword is used with the Finally block is always related to finalize() method is used with the
to classes, methods and variables. the try and catch block in exception objects.
handling.

3. Functionality (1) Once declared, final variable (1) finally block runs the important finalize method performs the
becomes constant and cannot be code even if exception occurs or cleaning activities with respect to
modified. not. the object before its destruction.
(2) final method cannot be (2) finally block cleans up all the
overridden by sub class. resources used in try block
(3) final class cannot be inherited.

4. Execution Final method is executed only Finally block is executed as soon as finalize method is executed just
when we call it. the try-catch block is executed. before the object is destroyed.

It's execution is not dependant on


the exception.

13. Difference between Throw & Throws?

14. What is static block?

15. What is Array list and method used in this?

16. What is upcasting & downcasting?

17. What is Wrapper class?

18. Difference between List, Set & Map?

19. Difference between Method overloading & overriding?

20. What is arithmetic exception?

Anything divide by 0 (3/0 or i/0) will give arithmetic exception in Java. 1/0 is infinite, Infinite cannot
be handled in Java.

Include Catch block (NullPointerException), after arithmetic exception, exception will not catch it
because of null pointer, even then Fianally block will get execute.

21. Difference between Abstract class and Interface?

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8, it can
abstract methods. have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non- Interface has only static and final variables.
static variables.

4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract class.
interface.

5) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.

6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.

7) An abstract class can be extended using keyword An interface can be implemented using keyword "implements".
"extends".
8) A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

22. Difference between throw and throws?

Throw keyword is used to throw an exception explicitly. It can throw only one exception at a
time. The throws keyword can be used to declare multiple exceptions, separated by a comma.

Throw and throws are the concepts of exception handling in Java where the throw keyword throws
the exception explicitly from a method or a block of code, whereas the throws keyword is used in
the signature of the method.

The throw keyword is used inside a The throws keyword is used in the function
function. It is used when it is required to signature. It is used when the function has some
1. Point of Usage throw an Exception logically. statements that can lead to exceptions.

The throws keyword can be used to declare


The throw keyword is used to throw an multiple exceptions, separated by a comma.
Exceptions exception explicitly. It can throw only one Whichever exception occurs, if matched with
2. Thrown exception at a time. the declared ones, is thrown automatically then.

Syntax of throw keyword includes the Syntax of throws keyword includes the class
instance of the Exception to be thrown. names of the Exceptions to be thrown. Syntax
Syntax wise throw keyword is followed by wise throws keyword is followed by exception
3. Syntax the instance variable. class names.

throw keyword cannot propagate checked


exceptions. It is only used to propagate the
Propagation unchecked Exceptions that are not throws keyword is used to propagate the
4. of Exceptions checked using the throws keyword. checked Exceptions only.

23. What is THIS in java?

In Java, this is a reference variable that refers to the current object. This keyword refers to the
current object in a method or constructor.

6 usage of java this keyword.


1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

24. What is Super in Java?

Super and this keyword super() as well as this() keyword both are used to make constructor
calls. super() is used to call Base class's constructor(i.e, Parent's class) while this() is used to call the
current class's constructor.

Super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

25. Different ways to refresh page?


driver.navigate().refresh();
driver.get(driver.getCurrentUrl());

Javascript executor:
JavascriptExecutor executor = (JavascriptExecutor) driver;
//(JavascriptExecutor) this means type casting
Executor.executescript(“location.reload”);// or use
history.go(0);

Robot class f5:


Robot robot = new Robot();
Robot.Keypress(keyEvent.VK_F5); //VK = Virtual Key
Robot.KeyRelease(keyEvent.VK_F5);
driver.findElement(By.name("s")).sendKeys(Keys.F5);// use ASCI value
/uE035

How to get current URL of a Page:


driver.get(driver.getCurrentUrl());
driver.navigate().to(driver.getCurrentUrl());
26. How to create string object in java?

In Java, a string is an object that represents a number of character values. Each letter in the string is
a separate character value that makes up the Java string object. Characters in Java are represented
by the char class.

There are two ways to create a String object:


1. By string literal: Java String literal is created by using double quotes. For Example: String
s=“Welcome”;
2. By new keyword: Java String is created by using a keyword “new”. For example: String s=new
String(“Welcome”);

Java String length(): The Java String length() method tells the length of the string. It returns count of
total number of characters present in the String.

Java String compareTo(): The Java String compareTo() method compares the given string with
current string.

27. Maven Lifecycle?

Each of these build lifecycles is defined by a different list of build phases, wherein a build phase
represents a stage in the lifecycle.
For example, the default lifecycle comprises of the following phases (for a complete list of the
lifecycle phases, refer to the Lifecycle Reference):

 validate - validate the project is correct and all necessary information is available
 compile - compile the source code of the project
 test - test the compiled source code using a suitable unit testing framework. These tests
should not require the code be packaged or deployed
 package - take the compiled code and package it in its distributable format, such as a JAR.
 verify - run any checks on results of integration tests to ensure quality criteria are met
 install - install the package into the local repository, for use as a dependency in other
projects locally
 deploy - done in the build environment, copies the final package to the remote repository for
sharing with other developers and projects.

28. Can we overload main and override?


You should know that overloading takes place at compile time and overriding takes place at
runtime.

it's possible to overload main in Java but it's not possible to override it, simply because it's a
static method. JVM always calls the original main method and if it doesn't found in class then it
throws java.lang.NoSuchMethodError: main Exception in thread "main" error at runtime.

Overloading means the same method name but different parameters, and
overriding means the same method name in a subclass with the same
parameters. So its not possible for overloading and overriding to happen at
the same time because overloading implies different parameters.
29. Can we overload and override constructor?
No it is not possible to override a constructor. If we try to do this then compiler error will come.
And it is never possible in Java.

30. Constructor in Java?


A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object
attributes.
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling the constructor, memory for the object is allocated in
the memory. It is a special type of method which is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called.
Note: It is not necessary to write a constructor for a class. It is because java compiler creates a
default constructor (constructor with no-arguments) if your class doesn’t have any.
How Constructors are Different from Methods in Java?
 Constructors must have the same name as the class within which it is defined it is not
necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type or void if does not
return any value.
 Constructors are called only once at the time of Object creation while method(s) can be
called any number of times.
Types of Constructors in Java
 No-argument constructor
 Parameterized Constructor
 Default Constructor

31. What is static in Java?


Static is a keyword that is used for memory management mainly. Static means single copy
storage for variables or methods.
The members that are marked with the static keyword inside a class are called static members.
When a method is declared with the keyword ‘static’, it is called static method in java.
The main use of java static keyword is as follows:
 The static keyword can be used when we want to access the data, method, or block of
the class without any object creation.
 It can be used to make the programs more memory efficient.
We cannot mark a local variable with a static keyword.
32. Frames in selenium?
A frame is identified with <frame> tag in the html document. A frame is used to insert an HTML
document inside another HTML document.

driver.switchTo().frame(1), we shall switch to the frame with index 1.


driver.switchTo().frame("fname"), we shall switch to the frame with name
fname.
switchTo().defaultContent() – To switch back to the main page from the frame.
driver.switchTo().defaultContent()
driver.switchTo().activeElement() // This will switch to active element like
search box in google page -
driver.switchTo().activeElement().sendkeys(“Searchterm \n”);

33. Excel Read-Write using Apache POI in Selenium?

Apache POI in Selenium is a widely used API for selenium data driven testing API that offers a
collection of Java libraries that helps us to read, write, and manipulate different Microsoft files such
as excel sheets, power-point, and word files.Users can easily create, modify and read/write into
excel files. POI stands for “Poor Obfuscation Implementation.”

Apache POI uses certain terms to work with Microsoft Excel.

Term Details
A workbook represents a Microsoft Excel file. It can be used
Workb
for creating and maintaining the spreadsheet. A workbook
ook
may contain many sheets.
A sheet refers to a page in a Microsoft Excel file that
Sheet
contains the number of rows and columns.
A row represents a collection of cells, which is used to
Row
represent a row in the spreadsheet.
A cell is indicated by a row and column combination. Data
Cell entered by a user is stored in a cell. Data can be of the type
such as string, numeric value, or formula.

STEPS WITH JXL JARS:

1. Get File Location


2. Get Workbook
3. Get Sheet
4. Get Rows
5. Get Columns
6. Iterate and get cell values.
 Save as Excel 97-2003 file format, then only it’ll work in JXL.
@Dataprovider(name=”logindata”)

Public String[][] loginDataProvider(){

data = getExcelData();

return data(); }

Public String[][] getexceldata() {

FileInputStream excel = new FileInputStream(“C:\\Test Data location”);

Workbook workbook = workbook.getWorkbook(excel);

Sheet sheet = workbook.getSheet(0); // In getsheet() either we can directly


give sheet name or Index position

Int rowcount = Sheet.getRows(); //getRows() return Int return type

Int columncount = Sheet.getColumns(); //getColumns() return Int return type


String testdata[][] = new String[rowcount-1][columncount]; //[][] means 2
dimensional array, rowcount-1 will eliminate the row headings

For(int i=1; i<rowcount; i++){

for(int j=0; j<columncount; j++) {

testdata[i-1][j] = sheet.getCell(j,i).getContents(); // i&j are


position of cell value

}} return testdata; }

@Test(dataProvider=”logindata”)

Public void loginwithBothCorrect(String nName,String pword){

//Open browser and launch application to proceed

STEPS WITH APACHE POI JAR:

1. Read the File Location


2. Create object for Workbook
3. Go to Sheet to be worked on
4. Row iteration and get row values
5. Cell Iteration and get cell values.

 HSSF – Microsoft excel 2003 file // Excel version from 97-2003


 XSSF - Microsoft excel 2007 file or later // Excel version after 2007 means use XSSF
 XSSFWorkbook & HSSFWorkbook – Excel Workbook
 HSSFSheet & XSSFSheet – Are classes which act as an excel worksheet
 Row defines an excel row
 Cell defines an excel cell addressed in reference to a row
Public Class DataDrivenUsingPOI(){

Public void readExcel(){

FileInoutStream excel = new FileInputStream(“File Location”);

Workbook workbook = new XSSFWorkbook(excel); // Excel latest version

Sheet sheet = workbook.getSheet(0);


Iterator<ROW> rowIterator = Sheet.iterator(); //Iterator return type
is row

While(rowiterator.hasnext()){

Row rowvalue = rowiterator.next();

Iterator<Cell> columniterator = rowvalue.iterator();

While(columniterator.hasnext()){

Cell columnvaule = columniterator.next();}}}

Public void main(String[] args){

DataDrivenUsingPOI usingPOI = new DataDrivenUsingPOI();

usingPOI.readexcel();

File Writing in JAVA:

File writer – Straight forward,direct interaction with files – Performance issue long codes,repeat line

Buffered Writer – Easiest Way, performance wise better and widely used

FileOutputStream – For writing raw byte array information (eg: images)

Path – Written by byte array


//1. File Location 2. Content required for file writing usind FileWriter
String Location = “FileWriter.txt”; //Either we can give local drive
location or we can write directly inside the Java Project Folder

String content = “FileWriter Test Data”;

FileWriter filewriter = new FileWriter(Location);

Filewriter.writer(content);

Filewriter.close();

// Buffered Writer sample code


String Location = “FileWriter.txt”;

String content = “FileWriter Test Data”;

FileWriter filewriter = new FileWriter(Location);

BufferWriter bufferwriter = new BufferWriter(filewriter); // Passing the


file object “filewriter” inside the BufferWriter

BufferWriter.writer(content);

BufferWriter.close();

// File Output Stream sample code


String Location = “FileWriter.txt”;

String content = “FileWriter Test Data”;

FileOutputStream outputstream = new FileOutputStream(Location);


byte[] fileout = content.getbytes(); // getBytes() will be stored in byte[]
array

outputstream.writer(fileout);

outputstream.close();

// Path sample code


String Location = “FileWriter.txt”;

String content = “FileWriter Test Data”;

Path path = Paths.get(location);

Files.write(path, content.getBytes());

File Reading in JAVA:

Buffered Reader – Easiest & simplest way, performance wise better and widely used
//1.For file reading we need location,

//2.we need to create an object for filereader,

//3.pass the location to tat object

//4.Buffer reader to read the file

//5.create an object for buffer reader

//6.pass filereader to tat object

//7. To read each line we need to “reader.readline()”- To read


multiplelines, put this reader.readline() in while loop

String Location = “FileWriter.txt”;

FileReader filereader = new FileReader(Location);

BufferReader bufferreader = new BufferReader(filereader); // Passing the


file object “filereader” inside the BufferWriter

String currentline = reader.readline();// readline()return type is string

Sys.out.print(“currentline”);

// To read multiple lines use while loop

String Location = “FileWriter.txt”;

FileReader filereader = new FileReader(Location);

BufferReader bufferreader = new BufferReader(filereader);

String currentline;

While((currentline = reader.readline())!=null){

Sys.out.print(“currentline”);}

TESTNG:
Verbose = numbers

It will display the level of information in Test Report table after executing the test cases using
TestNG Suite.

How to run a test cases in TestNG,

<Suite>

<Test>

<Parameter>

<Classes>

<Class name = “testNG.Testcase name”>

Close all the above

How to set priority, @Test(priority = 0)

How to skip a test case, @Test(priority=2, enabled=false)

How to set dependencies, @Test(dependsOnMethods= “Method Name”) to test in sequential


order.

How to get execution run time, long startTime= system.currentTimeMillis();

How to set parameter,

@Test

@Parameters(“Parameter Name”)

How to do parallel testing, Using Selenium Grid

How to do parallel testing using TestNG – VERY VERY VERY IMPORTANT

Include parallel in Suite -> <Suite name=”Test Suite” verbose =”2” Parallel = “methods”
thread count =”2”> // Thread means number of process in parallel testing

How to assert in TestNG, Assert.assertEquals( Actual, expected) /This is to check string values, If not
equals means will get Assertertion error

To check Boolean value using assert, Assert.assertTrue(Condition, Message)

TestNG Annotations & Hierarchy:

@BeforeSuite

@BeforeTest

@BeforeClass

@BeforeMethod

@AfterMethod
@AfterClass

@AfterTest

@AfterSuite

TestNG Listeners: It is an interface that modifies the TestNG behaviour. Listeners. When the test
case failure occurs, then it is redirected to the new block written for the screenshot. (SDET Video)

Listeners are implemented by the ITestListener interface.

Implements ITestListerners // ITestListerns is an interface & Implements is a Java keyword

ITestListeners has collections of different methods()

OnStart() //This will be run in the beginning

OnTestStart() //After OnStart only OnTestStart will happen

OnTestSuccess()

OnTestFailure()

OnTestSkip()

OnFinish()

How to Re-run Failed Test Cases using TestNG:

 We can manually run using testng-failed.xml // This will be created in Test Output folder
 Using IRetryAnalyzer Interface //This will create a Boolean retry method to run the test
under if condition to retry within the specified limit. This will execute @Test Level
 Using IAnnotationTransformer and IRetryAnalyzer //IAnnotationTransformer which is
dependent of IRetryAnalyzer, for this Listeners will be added in TestNG xml to retrieve the
testcases as per below. This will execute at Run Time.
<listener class name=”Package.Transformer”>

Public class RetryAnalyzer implements IRetryAnalyzer{


Int count=0;
Int retrylimit = 3;
Public Boolean retry(ITestResult result){
If(counter <retrylimit){
Counter++
Return true;
} retrun false; }

How to handle exceptions in TestNG – Using “expectedException = Exception Name.class”


//ExceptedException is an attribute

Significance of AlwaysRun attribute in TestNG – If a test case has a “dependsonmethod=another


test case” even if it throws exception, if user added “alwaysrun=true” attribute means it’ll run and
pass the test case
How to hit a URL without using GET or Navigate to methods:
Using javascript executor,

Window.location = ‘URL’

Sample Code:

String url = “http://www.google.com” // Saving a URL in a string

webdriverManager.Chromedriver().setup();

webdriver driver = new chromedriver();

JavascriptExecutor executor = (JavascriptExecutor) driver;

Executor.executescript(“window.location=\’ ”+url +”\’ ”); // Escape sequence = \’ ”+url +”\’ ”

Execute a test case multiple times with TestNG invocation Count

@Test(invocationCout = 3) // This invocationcount will rerun the same test multiple times as per
number entered

Public void test(){

System.println(“QWERTY”);

You might also like