A proxy server acts as an intermediary for requests between a client and a server. In simple terms, the traffic flows through the proxy server on its way to the address you requested and back.
A proxy server for automation scripts with Selenium could be helpful for:
Capture network traffic
Mock backend calls made by the website
Access the required website under complex network topologies or strict corporate restrictions/policies.
1. Create an instance of FirefoxOptions
FirefoxOptions options = new FirefoxOptions();
2. Set the desired preferences or proxy configuration
Create an instance of ChromeOptionsand set the proxy:
Replace “proxyAddress” with your actual proxy address and “proxyPort“ with the appropriate port number.
network.proxy.type is a preference that determines the type of proxy being used. It is a configuration option that can be set to different values to specify the proxy type.
Launch Firefox WebDriver with the configured options:
driver = new FirefoxDriver(options);
The complete program is mentioned below:
package org.example;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class FireFoxProxyDemo {
public static void main(String[] args) {
// Set the proxy server details
String proxyAddress = "localhost";
int proxyPort = 8080;
FirefoxDriver driver;
// Create an instance of `FirefoxOptions` and set the proxy configuration
FirefoxOptions options = new FirefoxOptions();
options.addPreference("network.proxy.type", 1);
options.addPreference("network.proxy.http", proxyAddress);
options.addPreference("network.proxy.http_port", proxyPort);
// Instantiate FireFox Driver with the configured options
driver = new FirefoxDriver(options);
// Perform your browsing actions using the driver
driver.get("https://www.google.com");
System.out.println("Page Title :" + driver.getTitle());
// Close the browser session
driver.quit();
}
}
The output of the above program is
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Selenium Quiz 3 – You can test your knowledge with this Selenium Quiz. We have created this Selenium WebDriver Quiz Online Test to help you master Selenium.
13. Consider the web page is still loading, and the element is not yet on the screen at the time of the find operation. What would be the exception thrown by the WebDriver?
Selenium Quiz – You can test your knowledge with this Selenium Quiz. We have created this Selenium WebDriver Quiz Online Test to help you master Selenium.
1. Which of the following browsers supports selenium?.
Selenium Quiz – You can test your knowledge with this Selenium Quiz. We have created this Selenium WebDriver Quiz Online Test to help you master Selenium.
1. What is selenium, select the best answer.
Select the best answer
Selenium is the open-source test automated tool to test web-based UI which only supports JavaScript’s
Selenium is the open-source test automated tool to test web-based UI which supports many different languages like Java, Python, Perl, PHP, Ruby, and C#.
Selenium is a behavioral testing tool that supports many different languages like Java, Python, Perl, PHP, Ruby, and C#.
A proxy server acts as an intermediary for requests between a client and a server. In simple terms, the traffic flows through the proxy server on its way to the address you requested and back.
A proxy server for automation scripts with Selenium could be helpful for:
Capture network traffic
Mock backend calls made by the website
Access the required website under complex network topologies or strict corporate restrictions/policies.
1. Setting up Proxy using Selenium
Create an instance of Proxy and set the proxy configuration:
// Set the proxy server details
String proxyAddress = "proxy.example";
int proxyPort = 8080;
// Create a Proxy object and set the HTTP proxy details
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
Replace “your_proxy_address” with the actual proxy address and “port” with the appropriate port number.
setHttpProxy – Specify which proxy to use for HTTP connections
2. Configure Chrome options with the Proxy object
Create an instance of ChromeOptionsand set the proxy:
ChromeOptions options = new ChromeOptions();
options.setProxy(proxy);
Launch Chrome WebDriver with the configured options:
WebDriver driver = new ChromeDriver(options);
The complete program is mentioned below:
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ProxyDemo {
public static void main(String[] args) {
// Set the proxy server details
String proxyAddress = "localhost";
int proxyPort = 8080;
// Create a Proxy object and set the HTTP proxy details
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
// Configure Chrome options with the Proxy object
ChromeOptions options = new ChromeOptions();
options.setProxy(proxy);
options.addArguments("start-maximized");
// Instantiate ChromeDriver with the configured options
WebDriver driver = new ChromeDriver(options);
// Perform your browsing actions using the driver
driver.get("https://www.google.com");
System.out.println("Page Title :" + driver.getTitle());
// Close the browser session
driver.quit();
}
}
In the previous tutorial, I explainedSerenity BDD with Cucumber for Web Application. In this tutorial, I will explain the Integration of Serenity with JUnit4. This tutorial gives an idea of how to set up a new project where we like to use Serenity as BDD Framework and JUnit as a Testing framework.
This project consists of various classes – ApplicationLoginTests (This is the Test Class which is going to contain all the tests). NavigationActions is the Action class that is used to open the webpage or application. StepLoginPage, StepDashboardPage, and StepForgotPasswordPage are the Page Object classes that contain multiple functionalities of that page and that help to keep the code clean.
Implementation Steps
Step 1 – Update the Properties section
Update the Properties section in Maven pom.xml, in case of Maven project.
The Test Class – ApplicationLoginTests is created under src/test/java directory.
package org.example.tests;
import net.serenitybdd.annotations.Pending;
import net.serenitybdd.annotations.Steps;
import net.serenitybdd.annotations.Title;
import net.serenitybdd.core.Serenity;
import net.serenitybdd.junit.runners.SerenityRunner;
import org.example.steps.StepDashBoardPage;
import org.example.steps.StepForgotPasswordPage;
import org.example.steps.StepLoginPage;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertTrue;
@RunWith(SerenityRunner.class)
public class ApplicationLoginTests {
@Steps
NavigateActions navigate;
@Steps
StepLoginPage loginPage;
@Steps
StepDashBoardPage dashboardPage;
@Steps
StepForgotPasswordPage forgetPasswordPage;
@Test
@Title("Login to application with invalid credential generates error message")
public void invalidCredentials() {
// Given
navigate.toTheHomePage();
// When
loginPage.inputUserName("Admin");
loginPage.inputPassword("admin");
loginPage.clickLogin();
// Then
Serenity.reportThat("Passing invalid credentials generates error message",
() -> assertTrue(loginPage.errorMessage().equalsIgnoreCase("Invalid Credentials")));
}
@Test
@Title("Login to application with valid credentials navigates to DashBoard page")
public void successfulLogin() {
navigate.toTheHomePage();
// loginPage.open();
// When
loginPage.inputUserName("Admin");
loginPage.inputPassword("admin123");
loginPage.clickLogin();
// Then
Serenity.reportThat("Passing valid credentials navigates to DashBoard page",
() -> assertTrue(dashboardPage.getHeading().equalsIgnoreCase("DashBoard")));
}
@Test
@Pending
@Title("Verify Forgot your password link")
public void clickForgetPasswordLink() {
// Given
navigate.toTheHomePage();
// When
loginPage.clickForgetPasswordLink();
// Then
Serenity.reportThat("Open Forget Password Page after clicking forget password link",
() -> assertTrue(forgetPasswordPage.getHeadingForgetPasswordPage().equalsIgnoreCase("Reset Password")));
}
}
The tests run using the Serenity test runner – @RunWith(SerenityRunner.class).
The @Steps annotation marks a Serenity step library.
Create the test following the Given/When/Then pattern and using step methods from the step library.
The @Title annotation lets you provide your own title for this test in the test reports.
Step 5 – Create the Action class
Create NavigateActions class under src/test/java. This class is used to open a web browser with the URL specified. This class is extended from UIInteractionSteps.
openPageNamed() method opens an environment-specific page defined in the serenity.conf file under the pages section. The value of loginForm is derived from serenity.config:
package org.example.tests;
import net.serenitybdd.annotations.Step;
import net.serenitybdd.core.steps.UIInteractionSteps;
public class NavigateActions extends UIInteractionSteps {
@Step
public void toTheHomePage() {
// openUrl("https://opensource-demo.orangehrmlive.com/");
openPageNamed("loginForm");
}
}
The JUnit Serenity integration provides some special support for Serenity Page Objects. In particular, Serenity will automatically instantiate any PageObject fields in the JUnit test. When a field of type StepLoginPage is declared in the test, Serenity instantiates it for you. The page is automatically instantiated and ready to be used.
@Managed
WebDriver driver;
@Managed declares a WebDriver instance that will be managed by Serenity. The WebDriver instance will be initialized automatically.
The driver parameter lets you define what WebDriver driver you want to run these tests in. Possible values include Firefox, chrome, iexplorer, phantomjs, appium, safari, edge, and htmlunit. The default browser in Serenity is Firefox. There are multiple ways to configure webDriver. One of the ways is to mention with @Managed as shown below:
@Managed(driver="chrome")
Step 7 – Create the serenity.conf file
Serenity.conf file is used to specify various features like the type of webdriver used, various test environments, run test in headless mode, and many more options. Serenity.conf can also contain settings like start size, disable sandbox, disable gpu, and others that need to be added to chrome.switches setting. Create serenity.conf file under src/test/resources.
The serenity.properties file is created at the root of the project.
serenity.project.name = Serenity and Junit4 Demo
Step 9 – Run the tests through the command
Open the command line and go to the location where the pom.xml of the project is present and type the below command.
mvn clean verify
Below is the execution status.
Step 10 – View the Serenity Reports
There are 2 types of reports are generated – Index.htmland Serenity-Summary.html.
Index.html
We can see the value of the @Title annotation, ‘Login to the application with valid credentials navigates to DashBoard page’, added as the heading. The value of @Step annotation, ‘Enter Username’, and ‘Enter Password’ is added to the Report as various steps.
This report contains a screenshot of each step also.
Emailable Report (Serenity-Summary.html)
These reports are present under /target/site/serenity.
Skipping the tests
In Serenity, you use the @Pending annotation, either for a test or for a @Step-annotated method, to indicate that the scenario is still being implemented and that the results are not available yet. These tests appear as ‘Pending’ (shown in blue) in the test reports.
@Test
@Pending
@Title("Verify Forgot your password link")
public void clickForgetPasswordLink() {
// Given
loginPage.open();
// When
loginPage.clickForgetPasswordLink();
// Then
Assert.assertTrue(forgetpasswordPage.ForgetPasswordPage());
}
The output of the above program is
Tests marked with@Ignorewill appear as ‘Ignored’ (from JUnit) and appears as grey in the test reports.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
In this tutorial, I will explain Parallel Testing using Cucumber with TestNG.
Cucumber-JVM allows parallel execution across multiple threads since version 4.0.0. There are several options to incorporate this built-in feature in a Cucumber project. You can do so by using JUnit, TestNG, or CLI.
Cucumber can be executed in parallel using TestNG and Maven test execution plugins by setting the data providerparallel option to true.
In TestNG, the scenarios and rows in a scenario outline are executed in multiple threads. One can use either Maven Surefire or Failsafe plugin for executing the runners. In this tutorial, I’m using the Maven Surefire plugin.
Feature: Login to HRM Application
Background:
Given User is on Home page
@ValidCredentials
Scenario: Login with valid credentials - Feature 1, Scenario -1
When User enters username as "Admin" and password as "admin123"
Then User should be able to login successfully
@InvalidCredentials
Scenario Outline: Login with invalid credentials - Feature 1, Scenario -2
When User enters username as "<username>" and password as "<password>"
Then User should be able to see error message "<errorMessage>"
Examples:
| username | password | errorMessage |
| Admin | admin12$$ | Invalid credentials |
| admin$$ | admin123 | Invalid credentials |
| abc123 | xyz$$ | Invalid credentials |
ForgotPasswordPage.feature
Feature: Forgot Password Page
Background:
Given User is on Home page
@BackFunctionality
Scenario: Validate the cancel functionality - Feature 2, Scenario - 1
When User clicks on Forgot your password? link
Then User should be able to navigate to Reset Password page
And User clicks on Cancel button to go back to Login Page
@ResetFunctionality
Scenario: Validate the Reset Password functionality - Feature 2, Scenario - 2
When User clicks on Forgot your password? link
Then User should be able to navigate to Reset Password page
And User clicks on Reset Password button and provide username as "abc1234"
And Verify the message "Reset Password link sent successfully"
Step 6 – Create Page Object Model classes of both feature files
Page Object Model class contains all the locators and the actions performed on these locators for the particular class to improve the readability and maintainability of the code.
Below are the Page Object Model classes for these feature files.
LoginPage
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
public WebDriver driver;
By userName = By.name("username");
By passWord = By.name("password");
By login = By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/form/div[3]/button");
By errorMessage = By.xpath("//*[@class='orangehrm-login-error']/div[1]/div[1]/p");
By forgotPasswordLink = By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/div[2]/form/div[4]/p");
By loginPageTitle = By.xpath("//*[@id='app']/div[1]/div/div[1]/div/div[2]/h5");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public String getErrorMessage() {
return driver.findElement(errorMessage).getText();
}
public void login(String strUserName, String strPassword) {
// Fill user name
driver.findElement(userName).sendKeys(strUserName);
// Fill password
driver.findElement(passWord).sendKeys(strPassword);
// Click Login button
driver.findElement(login).click();
}
// Click on Forgot Password link
public void clickOnForgotPasswordLink() {
driver.findElement(forgotPasswordLink).click();
}
//Get Login Page Title
public String getLoginPageTitle() {
return driver.findElement(loginPageTitle).getText();
}
}
HomePage
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class HomePage {
public WebDriver driver;
public HomePage(WebDriver driver) {
this.driver = driver;
}
By homePageUserName = By.xpath("//*[@class='oxd-topbar-header-breadcrumb']/h6");
public String getHomePageText() {
return driver.findElement(homePageUserName).getText();
}
}
ForgotPasswordPage
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class ForgotPasswordPage {
WebDriver driver;
By forgotPasswordPageTitle = By.xpath("//*[@id='app']/div[1]/div[1]/div/form/h6");
By cancelBtn = By.xpath("//*[@id='app']/div[1]/div[1]/div/form/div[2]/button[1]");
By resetPasswordBtn = By.xpath("//*[@id='app']/div[1]/div[1]/div/form/div[2]/button[2]");
By userName = By.name("username");
By resetMessage = By.xpath("//*[@id='app']/div[1]/div[1]/div/h6");
public ForgotPasswordPage(WebDriver driver) {
this.driver = driver;
}
// Get the Title of ForgotPage
public String getForgotPageText() {
return driver.findElement(forgotPasswordPageTitle).getText();
}
// Click Cancel Button
public void clickOnCancelBtn() {
driver.findElement(cancelBtn).click();
}
// Click ResetPassword Button
public void clickOnRestPasswordBtn() {
driver.findElement(resetPasswordBtn).click();
}
// Type username in TextBox
public void TypeOnUsernameTextBox(String username) {
driver.findElement(userName).sendKeys(username);
}
// Get Message
public String getRestMessage() {
return driver.findElement(resetMessage).getText();
}
}
PageObjectManager – This class creates the object of all the above-mentioned Page Object Model classes. This an optional class. If you want you can create the objects in StepDefinition class also.
public class PageObjectManager {
public LoginPage loginPage;
public HomePage homePage;
public ForgotPasswordPage forgotPasswordPage;
public WebDriver driver;
public PageObjectManager(WebDriver driver)
{
this.driver = driver;
}
public LoginPage getLoginPage()
{
loginPage= new LoginPage(driver);
return loginPage;
}
public HomePage getHomePage()
{
homePage = new HomePage(driver);
return homePage;
}
public ForgotPasswordPage getForgotPasswordPage()
{
forgotPasswordPage = new ForgotPasswordPage(driver);
return forgotPasswordPage;
}
}
Step 7 – Create the Step Definition classes for both feature files or Glue Code
Below is the Step Definition for LoginPage.feature.
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pageObjects.HomePage;
import pageObjects.LoginPage;
import pageObjects.PageObjectManager;
import utils.TestSetUp;
import org.testng.Assert;
public class LoginPageDefinitions {
TestSetUp setUp;
public PageObjectManager pageObjectManager;
public LoginPage loginPage;
public HomePage homePage;
public LoginPageDefinitions(TestSetUp setUp) {
this.setUp = setUp;
this.loginPage = setUp.pageObjectManager.getLoginPage();
this.homePage= setUp.pageObjectManager.getHomePage();
}
@Given("User is on Home page")
public void loginTest() throws IOException {
setUp.baseTest.WebDriverManager().get("https://opensource-demo.orangehrmlive.com/");
}
@When("User enters username as {string} and password as {string}")
public void goToHomePage(String userName, String passWord) {
// login to application
loginPage.login(userName, passWord);
// go the next page
}
@Then("User should be able to login successfully")
public void verifyLogin() {
// Verify home page
Assert.assertTrue(homePage.getHomePageText().contains("Dashboard"));
}
@Then("User should be able to see error message {string}")
public void verifyErrorMessage(String expectedErrorMessage) {
// Verify home page
Assert.assertEquals(loginPage.getErrorMessage(),expectedErrorMessage);
}
}
Below is the Step Definition for ForgotPasswordPage.feature.
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import pageObjects.ForgotPasswordPage;
import pageObjects.LoginPage;
import pageObjects.PageObjectManager;
import utils.TestSetUp;
import org.testng.Assert;
public class ForgotPasswordPageDefinitions{
TestSetUp setUp;
PageObjectManager pageObjectManager;
public LoginPage loginPage;
public ForgotPasswordPage forgotPasswordPage;
public ForgotPageDefinitions(TestSetUp setUp) {
this.setUp = setUp;
this.loginPage = setUp.pageObjectManager.getLoginPage();
this.forgotPasswordPage = setUp.pageObjectManager.getForgotPasswordPage();
}
@When("User clicks on Forgot your password? link")
public void forgotPasswordLink() {
loginPage.clickOnForgotPasswordLink();
}
@Then("User should be able to navigate to Reset Password page")
public void verifyForgotPasswordPage() {
Assert.assertEquals(forgotPasswordPage.getForgotPageText(),"Reset Password");
}
@Then("User clicks on Cancel button to go back to Login Page")
public void verifyCancelBtn() {
forgotPasswordPage.clickOnCancelBtn();
Assert.assertEquals(loginPage.getLoginPageTitle(),"Login");
}
@Then("User clicks on Reset Password button and provide username as {string}")
public void verifyResetPasswordBtn(String username) {
forgotPasswordPage.TypeOnUsernameTextBox(username);
forgotPasswordPage.clickOnRestPasswordBtn();
}
@Then("Verify the message {string}")
public void verifyMessage(String message) {
Assert.assertEquals(forgotPasswordPage.getRestMessage(),message);
}
}
Step 8 – Create the Hook Class and Dependency Injection class (TestSetUp) and BaseTest class
Below is the code for the ApplicationHook Class.
import io.cucumber.java.After;
import utils.TestSetUp;
public class ApplicationHooks {
public TestSetUp setUp;
public ApplicationHooks(TestSetUp setUp) {
this.setUp = setUp;
}
@After
public void tearDown( ) throws IOException {
setUp.baseTest.WebDriverManager().quit();
}
}
Below is the code for the Dependency Injection class. In Cucumber, if we want to share the state between multiple-step definition files, we will need to use dependency injection (DI).
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import pageObjects.PageObjectManager;
public class TestSetUp {
public WebElement errorMessage;
public WebElement homePageUserName;
public PageObjectManager pageObjectManager;
public BaseTest baseTest;
public TestSetUp() {
baseTest = new BaseTest();
pageObjectManager = new PageObjectManager(baseTest.WebDriverManager());
}
}
BaseTest class is used to initialize the WebDriver.
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
public class BaseTest {
public WebDriver driver;
public final static int TIMEOUT = 10;
public WebDriver WebDriverManager () {
if (driver == null) {
ChromeOptions options = new ChromeOptions();
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(TIMEOUT));
driver.manage().window().maximize();
driver.get(url);
}
return driver;
}
}
Step 9 – Create a Cucumber TestNG Runner class
Add a cucumber runner by extending the AbstractTestNGCucumberTests class and overriding the scenarios method. Set the parallel option value to true for the DataProvider annotation.
import io.cucumber.testng.AbstractTestNGCucumberTests;
import io.cucumber.testng.CucumberOptions;
import org.testng.annotations.DataProvider;
@CucumberOptions(tags = "", features = "src/test/resources/features", glue = "org.example.definitions")
public class CucumberRunnerTests extends AbstractTestNGCucumberTests {
@Override
@DataProvider(parallel = true)
public Object[][] scenarios() {
return super.scenarios();
}
}
Step 10 – Report Generation
Add cucumber.properties under src/test/resources and add the below instruction in the file.
cucumber.publish.enabled=true
Step 11 – Execute the test from Command Line
Use the below-mentioned command in the command prompt to run the tests.
mvn clean test
The output of the above program is
Step 12 – Execute the tests from TestNG Runner
Go to the Runner class and right-click Run As TestNG Test. The tests will run as TestNG tests. (Eclipse)
In the case of IntelliJ, right-click and select Run “CucumberRunnerTests”.
Step 13 – Test Execution Result
All the tests are started at the same time, so they share different threads. The way tests are executed is different in them. With non-parallel tests, all the scenarios of the same feature are executed together, and then the scenarios of another feature file. Whereas in parallel tests, all the tests are started at the same time, so there won’t be any specific order.
All the scenarios have started simultaneously.
The Cucumber Report is shown below:
There are chances that we don’t want to run all the scenarios simultaneously, in this case, we need to add the below-mentioned configuration in the pom.xml. The value =2 means that 2 scenarios will be executed simultaneously.
In the previous tutorial, it is explained how to automate Checkbox in Selenium. In this tutorial, we will learn how to handle Drop Down & Multiple Select Operations. DropDown & Multiple Select Operations work together and almost the same way. The only difference between these two deselecting statements & multiple selections is not allowed on DropDown.
To identify DropDown or multi-select list on a web page, we can use any one of the options like id, name, xpath, css, etc.
To perform any operation on DropDown, we need to do 2 things:-
1) Selenium WebDrivers provides a class called “Select “class that is used to automate dropdown, and it is imported from the package:
org.openqa.selenium.support.ui.Select
2) Create a new Select object of class Select.
Select oSelect = new Select());
We can access all the methods residing inside the SELECT class by typing oSelect + dot.
Different Select Commands
Before we discuss various select commands, we should know how the HTML code of DropDown actually looks
1) selectByVisibleText
selectByVisibleText(String arg0): void – Choose the option given under any dropdowns and multiple selection boxes with selectByVisibleText method. It takes a parameter of String that is one of the Value of Select element and it returns nothing.
To select the text One
select.selectByVisibleText("One");
2) selectByIndex
selectByIndex(int arg0): void – It is almost the same as selectByVisibleText but the only difference here is that we provide the index number of the option here rather than the option text. It takes a parameter of int which is the index value of the Select element and it returns nothing.
To select the value 3 using index
select.selectByIndex(3);
3) selectByValue
selectByValue(String arg0): void – It selects the option of the value. It takes a parameter of String that is of the value of the Select element and it returns nothing.
To select the value of two
Select mselect = new Select(driver.findElement(By.id("redirect")));
mselect.selectByValue("two");
Let us explain this with the help of an example.
1) Launch a new Browser and open “https://www.selenium.dev/selenium/web/formPage.html“ 2) Print the list of options in the dropdown. 3) Select option ‘One’ (Use selectByVisibleText) 4) Select option ‘3’ (Use selectByIndex) 5) Select option ‘two’ (Use selectByValue) 6) Close the browser
The complete program looks like as shown below:
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.Select;
import java.time.Duration;
import java.util.List;
public class DropDown_Demo {
public static void main(String[] args) {
// Initiate Firefox browser
FirefoxOptions firefoxOptions = new FirefoxOptions();
WebDriver driver = new FirefoxDriver(firefoxOptions);
// Implicit Wait
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
// Pass application url
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
//Get the list of options from dropdown
Select select = new Select(driver.findElement(By.name("select-default")));
List<WebElement> listElements = select.getOptions();
System.out.println("List of options in dropdown:" );
for(WebElement options: listElements)
System.out.println(options.getText());
// Select option 'Two' (Use selectByVisibleText)
System.out.println("Select the Option by Text - One");
select.selectByVisibleText("One");
// Select option '3' (Use selectByIndex)
System.out.println("Select the Option by Index 3 - Still learning how to count, apparently");
select.selectByIndex(3);
// Select option 'two' (Use selectByValue)
System.out.println("Select the Option by selectByValue - two");
Select mselect = new Select(driver.findElement(By.id("redirect")));
mselect.selectByValue("two");
// close the browser
driver.close();
}
}
The output of the above program is
Different DeSelect Methods
The way we select different values of DropDown and Multi Select, we can deselect the options similarly.
1) deselectAll
deselectAll( ): void – Clear all selected entries. This is only valid when the SELECT supports multiple selections.
Syntax:
oSelect.deselectAll;
2) deselectByIndex
deselectByIndex(int arg0): void –Deselect the option at the given index.
Syntax:
oSelect.deselectByIndex;
3) deselectByValue
deselectByValue(String arg0): void –Deselect all options that have a value matching the argument.
Syntax:
oSelect.deselectByValue;
4) deselectByVisibleText
deselectByVisibleText(String arg0): void – Deselect all options that display text matching the argument.
Syntax:
oSelect.deselectByVisibleText
Below is an example of how to operate on multi-selection options.
1) Launch a new Browser and open “https://www.selenium.dev/selenium/web/formPage.html“ 2) Print the list of options in the dropdown. 3) Select options ‘eggs’ and ‘sausages’. 4) Print and select all the options for the selected Multiple selection list. 5) Deselect option eggs. 6) Deselect all options 7) Close the browser
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.support.ui.Select;
import java.time.Duration;
import java.util.List;
public class MultiSelect_Demo {
public static void main(String[] args) {
// Initiate Firefox browser
FirefoxOptions firefoxOptions = new FirefoxOptions();
WebDriver driver = new FirefoxDriver(firefoxOptions);
// Implicit Wait
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
// Pass application url
driver.get("https://www.selenium.dev/selenium/web/formPage.html");
//Get the list of options from dropdown
Select select = new Select(driver.findElement(By.name("multi")));
List<WebElement> listElements = select.getOptions();
System.out.println("List of options in dropdown:");
for (WebElement options : listElements)
System.out.println(options.getText());
// Select option 'Ham' (Use selectByVisibleText)
System.out.println("Select the Option by Text - Eggs");
select.selectByVisibleText("Eggs");
// Select option '2' (Use selectByIndex)
System.out.println("Select the Option by Index 2 - Sausages");
select.selectByIndex(2);
System.out.println("*************************************");
//Get the list of selected options
System.out.println("The selected values in the dropdown options are -");
List<WebElement> selectedOptions = select.getAllSelectedOptions();
for(WebElement selectedOption: selectedOptions)
System.out.println(selectedOption.getText());
// Deselect the value "eggs" by Value
System.out.println("*************************************");
System.out.println("DeSelect option eggs by Value");
select.deselectByValue("eggs");
System.out.println("*************************************");
System.out.println("The latest selected values in the dropdown options are -");
List<WebElement> reselectedOptions = select.getAllSelectedOptions();
for(WebElement selectedOption: reselectedOptions)
System.out.println(selectedOption.getText());
select.deselectAll();
driver.quit();
}
}
The output of the above program is
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!