0% found this document useful (0 votes)
14 views20 pages

Selenium Java Automation Testing Guide

The document provides a comprehensive overview of Selenium and its application in automation testing, covering topics such as Selenium WebDriver basics, initialization of ChromeDriver, navigation commands, web elements, locators, and methods for interacting with web elements. It also outlines the benefits and limitations of Selenium, the suite of tools available, and includes a section on interview questions related to Selenium. Additionally, it details the steps for adding dependencies in pom.xml and provides examples of common methods used in Selenium automation scripts.

Uploaded by

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

Selenium Java Automation Testing Guide

The document provides a comprehensive overview of Selenium and its application in automation testing, covering topics such as Selenium WebDriver basics, initialization of ChromeDriver, navigation commands, web elements, locators, and methods for interacting with web elements. It also outlines the benefits and limitations of Selenium, the suite of tools available, and includes a section on interview questions related to Selenium. Additionally, it details the steps for adding dependencies in pom.xml and provides examples of common methods used in Selenium automation scripts.

Uploaded by

anusha bijukumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Selenium Java

 Introduction to Automation testing and Selenium

 Adding dependencies in [Link]

 Selenium WebDriver Basics

 Initialising chrome driver

 Methods

 Selenium Notes

 Navigation Command

 Web Elements

 Selenium Locators

 Methods used with Web Elements

 Locators and Syntax

 Select drop down Automation

 Action Class in Selenium

 Interview Questions
Automation testing
 “Automation testing is the process of using special tools or scripts to test software
automatically, without human intervention, to check whether it behaves as expected.”

 For Web Automation: Selenium, Cypress, Playwright.


 For API Automation: Postman with tests, Rest Assured.  For Mobile Testing: Appium,
Espresso.

BENEFITS OF AUTOMATION TESTING


 Fast and reliable
 Reusable scripts
 Early bug detection
 Support CI/CD

Selenium
 Selenium is an open-source automation tool used to test web applications across different
browsers and platforms.”

FEATURES OF SELENIUM
 Free and open source
 Support multiple browsers like chrome, edge, firefox, safari.
 Support multiple Operating Systems like Windows,MAC,Linux.
 Support multiple languages like Java,C#,PHP,Python,Ruby,JavaScripts.
 Support multibrowser testing and cross browser testing.

LIMITATIONS OF SELENIUM
 Doesn’t support automation testing for desktop applications.
 Knowledge of atleast one programming language to prepare test scripts is needed.
 Not possible to perform testing of images.
 Doesn’t automate newly designed features .
 Doesn’t automate frequently changing features.

SELENIUM-SUITE OF TOOLS
 4 VERSIONS ARE THERE.
1. Selenium 1 :- IDE,RC,GRID
2. Selenium 2:- IDE, Webdriver, RC,GRID
3. Selenium 3 :- IDE, Webdriver, GRID
4. Selenium 4 :- IDE, Webdriver, GRID(improved version of Selenium 3)

WebDriver
 It is a powerful web automation tool widely used in web application testing.
 It provides a programming interface to interact with web browser.
 Control browser behaviors like click, navigation and form submission through programs.
 Support different OS, browsers and programming languages
 Support cross browser and multibrowser testing.
IDE(INTEGRATED DEVELOPMENT ENVIRONMENT)
 Opensource web automation testing tool under Selenium suite.
 This is a record and play back tool.
 No need of programming language knowledge so non technical users can use this.
 Support in chrome and firefox.
 Used in quick testing.

GRID
 Opensource web automation testing tool under selenium suite
 Testcases can be executed in multiple machines in parallel so that we can reduce execution
time.
 Support cross browser testing and multibrowser testing.
 Support different OS, browsers and programming languages.

SAMPLE FLOW OF AUTOMATION TESTING


1. Write test cases.
2. Convert them to automation scripts.
3. Execute script using automation tools.(Eg: Selenium+TestNG)
4. Validate the result .( Tool :TestNG)
5. Generate the report.
6. Integrate with Jenkins for CI/CD.
Steps to Add a Dependency in [Link]
1. Search for the Dependency:
• Go to [Link] (search “maven repository” in Google).
• Type the name of the library (e.g., Selenium java, JUnit, Gson) in the search bar.
• Choose the latest stable version (avoid versions marked as beta, RC, or snapshot).
2. Copy the Dependency Tag:
• Copy the <dependency>...</dependency> XML snippet provided on the page.
3. Paste into [Link]:
• Open your project's [Link] file.
• Inside the <project> tag, find or create a <dependencies> block below the <version>
tag.
• Paste the copied dependency inside the <dependencies> tag.
Example
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>selenium-java</artifactId>
<version>4.21.0</version>
</dependency>
</dependencies>
4. Change http to https (Optional):
• If the repository URL inside the dependency block or repository block uses http,
change it to https for better security.
• This is usually needed only if you manually add a <repository> tag.
Example:
<repository>
<id>central</id>
<url>[Link]
</repository>
5. Save the [Link] file.
Selenium WebDriver Basics – ChromeDriver Initialization & Common
Methods

Initialising Chrome driver


WebDriver driver = new ChromeDriver();

➢ WebDriver is an interface in the Selenium API that defines standard methods for browser
automation (like .get(), .findElement(), .click(), etc.).

➢ ChromeDriver is a class that implements the WebDriver interface to control Google Chrome.
➢ driver is the reference variable (of type WebDriver) that points to the browser instance created by
new ChromeDriver().

Method to Open URL


[Link]("URL");

Example: [Link]("[Link]

Method to Maximize Browser Window


[Link]().window().maximize();

Methods to Close Browser Windows


[Link](); Closes only the current active browser window.

[Link](); Closes all browser windows opened during the Selenium session.

Method to get the title of current web page


[Link]();

Method to get the url of current web page


[Link]();

Method to get html code of current page


[Link]();
Selenium notes
Navigation Commands
In Selenium (Java), navigation commands are used to control the browser's navigation, such as
moving to a URL, going back, moving forward, or refreshing the page.

1. [Link]().to(String url);

eg: [Link]().to("[Link]
Navigate to a specific URL

2. [Link]().back();

Go to the previous page in the browser

3. [Link]().forward();

Go to the next page in the browser

4. [Link]().refresh();

Refresh the current page

Web Elements
• In Selenium, Web Elements refer to the HTML elements present on a web page (e.g.,
buttons, links, input fields, checkboxes).
• Selenium interacts with these elements using the WebElement interface.
• A WebElement is an object in Selenium that represents an HTML element on a web page.
• It is used to interact with buttons, text boxes, links, and other elements during automation
testing.

Selenium Locators
Locators in Selenium are used to find web elements on a web page. Selenium provides several types
of locators to identify elements uniquely.

1. id
2. name
3. className
4. tagName
5. linkText
6. partialLinkText
7. xpath
8. cssSelector.

Methods used with WebElements


In Selenium, WebElement provides various methods to interact with web page elements.

1. click() : Click on a button, link, checkbox, etc.

2. sendKeys(String text) : Enter text into an input field

3. getText() : Get the visible text of the element


Locators and Syntax

Locators
➢ There are 8 locators in Selenium
1. id
2. name
3. className
4. tagName
5. linkText
6. partialLinkText
7. cssSelector
8. xpath

CSS Selector

Combination Syntax

Tag and ID tag#id

Tag and Class [Link]

Tag and Attribute tag[attribute='value']

Tag, Class, and Attribute [Link][attribute='value']

xpath

Type Syntax
Relative XPath //tag[@attribute='value']
Contains //tag[contains(@attribute, 'partialValue')]
Starts-with //tag[starts-with(@attribute, 'startValue')]
text() //tag[text()='Exact Text']
contains(text()) //tag[contains(text(), 'Partial Text')]
AND //tag[@attr1='value1' and @attr2='value2']
OR //tag[@attr='value1' or @attr='value2']
Select drop down Automation
➢ In selenium, <select> dropdown is automated using Select class
1. Import Required Classes
2. Locate the Dropdown Element
WebElement dropdownElement = [Link]([Link]("dropdown-id"));

3. Create a Select Object and pass the dropdownElement


Select select = new Select(dropdownElement);

4. you can select an option in select drop down by using any of the three methods provided in
Select class
• [Link]("Option Text"); // e.g., "Red"

• [Link]("value1"); // e.g., value="Yellow"


• [Link](2); // Index starts from 0
Actions Class in Selenium

➢ The Actions class is used to handle advanced user interactions like:


• Mouse hover
• Drag and drop
• Right-click (context click)
• Double-click
• Click and hold
• Keyboard actions

➢ Example program for drag and drop action


[Link]().to("[Link]

// Locate source (draggable element)


WebElement dragField = [Link]([Link]("//span[text()='Draggable n°1']"));

// Locate target (drop zone)


WebElement dropField = [Link]([Link]("//div[@id='mydropzone']"));

// Create Actions object


Actions actions = new Actions(driver);

//method to drag and drop


[Link](dragField, dropField).perform();

Action Code Example Description


Drags element src and drops it
Drag and Drop [Link](src, dest).perform();
on dest.
Right-click (Context Performs a right-click on the
[Link](element).perform();
Click) given element.
Moves the mouse over the
Mouse Hover [Link](element).perform();
specified element (hover).
Performs a single left click on
Single Click [Link](element).perform();
the element.
Double Click Performs a double click on the
[Link](element).perform();
(Element) specified element.
Double Click Performs a double click at the
[Link]().perform();
(Anywhere) current mouse location.
Interview questions & answers
Q1) How do you initialise a browser in a selenium web driver?

 WebDriver driver = new ChromeDriver();


where
WebDriver : Interface
driver : Object / Reference Variable
ChromeDriver : Class

Q2) Which of the following statements are correct and why


1. WebDriver driver = new ChromeDriver();
2. ChromeDriver driver = new ChromeDriver();
3. WebDriver driver = new WebDriver();

 WebDriver driver = new ChromeDriver();


 most commonly used

 Flexible(We can change the browser later)
 ChromeDriver driver = new ChromeDriver(); ✅
 Also correct, but less flexible(You can only use Chrome with this reference.)
 WebDriver driver = new WebDriver(); ❌
 WebDriver is an interface and we cannot create object of interface

Q3) difference between [Link]("URL"); and [Link]().to("URL");

 [Link]("URL");
 Just opens the URL.
 Doesn't support forward, back, or refresh methods directly.
 [Link]().to("URL");
 Also opens the URL.
 Supports navigation methods like:
[Link]().back();
[Link]().forward();
[Link]().refresh();

Q4) What is the use of clear() in Selenium web element


 The .clear() method is used to clear the text from an input field or text area in a web page.
 Example
WebElement element = [Link]([Link]("input-field-id"));
[Link]();

 Use: When you want to remove existing text in a text box before typing new text using sendKeys().

Q5) Difference between id and name locator in selenium


 ID Locator
[Link]([Link]("element_id"));
 ID is unique on a webpage.
 Fastest and most reliable locator.
 Preferred when available.
 Name Locator
[Link]([Link]("element_name"));
 name might not be unique on a webpage.
 Slower and less reliable than id.
 Still useful when id is missing.

Q6) How do you maximise a browser window in selenium


 [Link]().window().maximize();

Q7) How to Close a Browser in Selenium


 [Link](); or [Link]();

 [Link](); //Close current window

 [Link](); //close all window

Q8) What are navigation commands


 Navigation commands allow us to move between pages and perform browser related
actions like going forward,, backward, refreshing.
 These commands are provided by the navigate() interface of the WebDriver.
 Example: [Link]().to("URL");, [Link]().back();, [Link]().forward();,
[Link]().refresh();

Q9) What interface and classes are involved in web driver initialisation
 Interface : webDriver
 Class : ChromeDriver

Q9) How do you navigate back to previous web page in seleniun


 [Link]().back();

Q10) How do you navigate to forward on a web page in selenium


 [Link]().forward();

Q11) How do you refresh a web page in selenium


 [Link]().refresh();

Q12) How do you fetch current page title in selenium


 [Link]();

Q13) How do you fetch the current page URL in Selenium


 [Link]();
Q14) What are web elements in selenium
 A WebElement represents an HTML element on a web page (like buttons, input fields, links, radio
button etc.).

 Selenium provides the WebElement interface to interact with these elements.

 You can click, type text, get text, check visibility, and more using WebElement methods.

Q15) How do you find a web element in selenium


 Selenium provides the findElement() method to locate a single web element on a web page.

 Example: WebElement element = [Link]([Link]("value"));

Q16) What is a Locator in Selenium?


 A locator in Selenium is a mechanism used to identify elements on a web page. That is, the locator
tells Selenium where and how to find a specific HTML element (like buttons, text fields, links, etc.)
so it can interact with them.

Q17) What are the different locators in selenium


 Selenium consist of 8 locators and they are:
1. id
2. name
3. className
4. tagName
5. linkText
6. partialLinkText
7. cssSelector
8. xpath

Q18) What are some common methods available in web element interface
 click();
 sendKeys();
 getText()

Q19) How do you interact with text box in selenium


 Using sendKeys();

Q20) How do you retrieve text from a web elements


 [Link]();
 It ignores hidden text (like inside display: none or visibility: hidden).

Q21) Difference between Absolute xpath and Relative xpath


 Absolute Xpath
 XPath that starts from the root (html) element
 Starts with single forward slash /
 breaks easily on any DOM change
 Used rarely, mostly in static pages
 Example: /html/body/div[2]/form/input
 Relative xpath
 XPath that starts from any node in the DOM
 Starts with double forward slash //
 More robust and flexible
 Preferred in real-time web automation
 Example: //input[@id='username']

Q22) How do you locate an element based on its visible text using XPath in Selenium?
 //tag name[text()=’value’]

Q23) How do you find a dynamic element in Selenium?


 Dynamic elements are web elements whose attributes (like id, name, class) change frequently or on
every page load. To locate them, we use robust XPath or CSS selectors that rely on stable parts of
the element.

 We can use Use contains() in XPath or starts-with() in XPath


 Example: //button[starts-with(@id, 'login_')]

Q24) How to click a Radio Button in Selenium?


 using click();

Q25) How to verify if a Radio Button is selected?


 You can use the isSelected() method to check whether a radio button is selected or not.
 Example:
WebElement maleRadio = [Link]([Link]("//input[@value='Male']"));

if ([Link]())
{
[Link]("Male radio button is selected.");
}
else
{
[Link]("Male radio button is NOT selected.");
}

Q26) How to Select a Specific Radio Button from a Group Using Its Value
 To select a specific radio button (e.g., "female") from a group, you can: Use findElements() to get
the list of all radio buttons sharing the same name.

 Use a loop to check each radio button's value attribute. Then click the one that matches the desired
value.

List<WebElement> radioButtons = [Link]([Link]("gender"));


for (WebElement button : radioButtons)
{
if ([Link]("value").equals("female"))
{
[Link]();
break; // Exit loop after clicking
}
}
Q27) What happens if you try to click a disabled Radio Button in Selenium?
 If you try to click a disabled radio button, Selenium will throw the following exception:
ElementNotInteractableException

Q28) Radio Button vs Checkbox in Selenium


 Radio Button
 Only 1 option can be selected at a time
 Used for Selecting one choice from a group

 Check Box
 Multiple options can be selected
 Can be used for Selecting multiple choices

Q29) How to uncheck a checkbox in Selenium


 WebElement checkbox = [Link]([Link]("subscribe"));
if ([Link]())
{
[Link](); // This will uncheck the checkbox
}

Q30) How to verify if a checkbox is selected or not


 Using isSelected();

Q31) What exception occurs if you try to click a disabled checkbox


 ElementNotInteractableException

Q32) How to count total number of checkboxes on a page


 List<WebElement> checkboxes = [Link]([Link]("//input[@type='checkbox']"));
[Link]("Total checkboxes: " + [Link]());

 size() gives the total count of elements in the list.

Q33) What is the Actions class in Selenium


 Actions is a class in Selenium that provides advanced user interactions such as mouse hover, right-
click, double-click, drag and drop, and keyboard events.

Q34) Why do we use the Actions class in Selenium


 The Actions class is used to:
✔️Perform mouse hover actions
✔️Handle drag and drop functionality
✔️Perform double-click and right-click (context click)

Q35) How do you create an object of the Actions class


 To use Actions, pass the WebDriver instance:
 Actions actions = new Actions(driver);

Q36) How do you perform a mouse hover action in Selenium


 Use the moveToElement() method to hover over an element
Q37) How do you perform a right-click in Selenium
 Use the contextClick() method:

Q38) How do you perform a double-click in Selenium


 Use the doubleClick() method

Q39) How do you perform a click using Actions class


 Use click():

Q40) difference between Static and Dynamic dropdowns in Selenium


 static dropdown
• uses select tag
• handled using select class
• Easy to automate

 Dynamic dropdown
• Build using Div, ui, li etc tags
• Complex to locate

Q41) How do you handle a dropdown in Selenium WebDriver


 Selenium provides the Select class to handle dropdowns that use the HTML <select> tag. This class
allows you to select options by visible text, value, or index.

Q42) What are the different methods to select a value from a dropdown
 1. selectByVisibleText(String text) //Selects the option by the text visible to the user.
2. selectByValue(String value) //Selects the option based on the value attribute in the HTML.

3. selectByIndex(int index) //Selects the option based on index position

Q43) How do you get all the options from a dropdown in Selenium
 You can use the getOptions() method of the Select class to retrieve all available options from a
<select> dropdown.

 Example:
Select select = new Select([Link]([Link]("dropdown")));
List<WebElement> options = [Link]();
for (WebElement option : options)
{
[Link]([Link]());
}

Q44) How do you verify if a dropdown allows multiple selections in Selenium


 Use the isMultiple() method of the Select class. It returns true if the dropdown allows multiple
selections, otherwise false.

 Select select = new Select([Link]([Link]("multi")));


[Link]([Link]()); // returns true or false
Q45) How do you deselect a selected value in a multi-select dropdown in Selenium
 Use the deselect methods provided by the Select class. These methods only work for multi-select
dropdowns.

 Select select = new Select([Link]([Link]("multi-select")));

// Deselect by index
[Link](1);

// Deselect by value
[Link]("val1");

// Deselect by visible text


[Link]("Option 1");

// Deselect all selected options


[Link]();

Q46) How do you handle custom dropdowns (non-<select> based) in Selenium


 Custom dropdowns are not based on the <select> tag, so the Select class cannot be used. You need
to manually interact with these dropdowns using click() and XPath or CSS selectors.

 Example
// Step 1: Click to open the dropdown
[Link]([Link]("customDropdown")).click();

// Step 2: Click the desired option


[Link]([Link]("//li[text()='Option 3']")).click();

Q47) Comparison: Static vs. Dynamic (Custom) Dropdowns


 Static Dropdown
• Html tag will be <select>
• Handled manual using click() and locators
• Easy to automate

 Dynamic Dropdown
• Html tag can be <div>, <ul>, <li>, etc.
• Handled using Select class
• Complex to automate

Q48) What exception do you get if dropdown is not a <select> tag and you use Select class
 **UnexpectedTagNameException**: Thrown when trying to use the Select class on a web element
that is not a <select> tag.

Q49) How to validate if a particular value is present in a dropdown


 Select select = new Select([Link]([Link]("dropdown")));
boolean found = false;
for (WebElement option : [Link]())
{
if ([Link]().equals("India"))
{
found = true;
break;
}
}
[Link]("Option present? " + found);
Alert Interview Questions
1. What is an alert in Selenium?

An alert is a popup box that appears on the screen, typically to display warnings or messages.
It can block interaction with the webpage until dismissed.

[Link] do you handle alerts in Selenium WebDriver?

Selenium provides the Alert interface for handling alerts.

[Link] to handle alerts

[Link](); → Click OK

[Link](); → Click Cancel

[Link](); → Get alert message

[Link]("text"); → Enter text (only for prompt alerts)

[Link] to accept a simple alert in Selenium?

Alert alert = [Link]().alert();

[Link](); // Clicks 'OK'

[Link] to accept a simple alert in Selenium?

Alert alert = [Link]().alert();

[Link](); // Clicks 'OK'

[Link] to dismiss a confirmation alert in Selenium?

Alert alert = [Link]().alert();

[Link](); // Clicks 'Cancel'

[Link] to retrieve text from an alert?

Alert alert = [Link]().alert();

String message = [Link]();

[Link](message);

[Link] to send input to a prompt alert?

Alert alert = [Link]().alert();

[Link]("Test Input");

[Link]();
[Link] is the difference between accept() and dismiss() methods in alert handling?

accept() clicks the OK button on alert.

dismiss() clicks the Cancel button on confirmation alerts.

[Link] is NoAlertPresentException in Selenium?

NoAlertPresentException is thrown when you try to switch to an alert using


[Link]().alert() but no alert is present on the webpage at that moment.

[Link] is UnhandledAlertException in Selenium?

This exception is thrown when there is an alert present, but the script tries to interact with
the webpage (like clicking or typing) without handling the alert first.

[Link] happens if you don’t handle an alert in Selenium?

If an alert is not handled and you try to interact with the web page, Selenium will throw an
UnhandledAlertException.

You might also like