

Select a Dropdown Option Using Selenium WebDriver in C#
source link: https://code-maze.com/csharp-select-a-dropdown-option-using-selenium-webdriver/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Select a Dropdown Option Using Selenium WebDriver in C#

We value your privacy
Select a Dropdown Option Using Selenium WebDriver in C#
Posted by Semir Teskeredzic | Dec 14, 2023 | 0
Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!
In this article, we will look at different ways to select a dropdown option using Selenium WebDriver in C#. We will use ASP.NET Core application and xUnit tests to showcase different approaches to our goal.
Let’s start.
What Is Selenium
When it comes to UI testing of web applications, we need to run them as real users would in their browsers. Perhaps the most popular open-source library is Selenium. It boasts the support of numerous modern web browsers and specific methods we use to write our tests.
Selenium can be used with xUnit to write automated UI tests for ASP.NET Core web applications, and in this article, we will cover the specific case to test a dropdown using Selenium WebDriver.
Project Setup
As a first step, we will create a simple ASP.NET Core Web App application in Visual Studio by selecting the ASP.NET Core Web App template.
Otherwise, we can create a new application using the .NET CLI:
dotnet new webapp
We will then implement a dropdown in Pages/Index.cshtml
:
<div class="text-center"> <h1 class="display-4">Programming Language Selector</h1> <form> <label>Select a Programming Language:</label> <select id="programming-language" name="programming-language"> <option value="csharp">C#</option> <option value="java">Java</option> <option value="python">Python</option> <option value="javascript">JavaScript</option> <option value="ruby">Ruby</option> <option value="php">PHP</option> <option value="go">Go</option> <option value="typescript">TypeScript</option> <option value="rust">Rust</option> </select> </form> </div>
Here, we add a standard <select>
element with multiple <option>
elements that we will use to demonstrate selecting a dropdown option using Selenium WebDriver. HTML tag attributes like IDs and classes are important to select elements in our test cases, so it’s important to note them.
Setting up the xUnit Test Project
Our next step is to create the xUnit test project inside our solution that will reference our ASP.NET Core web application.
We will install Selenium.WebDriver
, Selenium.WebDriver.ChromeDriver
, and Selenium.Support
libraries via NuGet Package Manager or using the .NET CLI:
dotnet add package Selenium.WebDriver Selenium.WebDriver.ChromeDriver Selenium.Support
WebDrivers drive browsers natively on a machine as a user would.
Our test project is now ready, so let’s write our tests.
Using the Element ID to Select a Dropdown Option Using Selenium
Let’s write our first test in the LiveTest
class:
using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; namespace SelectDropdownOptionUsingSeleniumWebDriverTests; public class SelectDropdownElementLiveTest { [Fact] public void GivenTestInChrome_WhenDropdownElementIsSelectedByText_ThenOptionValueIsReturned() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://localhost:7006/"); var dropdown = driver.FindElement(By.Id("programming-language")); var selectElement = new SelectElement(dropdown); selectElement.SelectByText("JavaScript"); Assert.Equal("javascript", selectElement.SelectedOption.GetAttribute("value")); driver.Quit(); } }
In our first test with ChromeDriver
, we navigate to the URL of our web application. Then, we find the element by the id "programming-language"
. Before we select the value for testing, we need to instantiate the SelectElement
class with the previously found element to interact with the dropdown.
Then, we can select the option we need, in this case using the SelectByText()
method. SelectByText()
will select all options with the displayed text in the browser. Lastly, we perform assertions to verify if the selection is successful and close the browser instance.
We need our web application running to run Selenium tests. So we must start the web application first and then open a terminal and run dotnet test
.
Our test passes as expected, which shows that we correctly selected "JavaScript"
option from the dropdown menu.
SelectByText()
is one of three methods available to us for selecting a dropdown option. We will create two more tests to demonstrate SelectByIndex()
and SelectByValue()
methods:
[Fact] public void GivenTestInChrome_WhenDropdownElementIsSelectedByIndex_ThenOptionValueIsReturned() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://localhost:7006/"); var dropdown = driver.FindElement(By.Id("programming-language")); var selectElement = new SelectElement(dropdown); selectElement.SelectByIndex(0); Assert.Equal("csharp", selectElement.SelectedOption.GetAttribute("value")); driver.Quit(); }
In this test, we select the option based on the int
index value. Index values begin with 0
, so to select the first value "csharp"
we use index 0
.
We continue with SelectByValue()
method:
[Fact] public void GivenTestInChrome_WhenDropdownElementIsSelectedByValue_ThenOptionValueIsReturned() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://localhost:7006/"); var dropdown = driver.FindElement(By.Id("programming-language")); var selectElement = new SelectElement(dropdown); selectElement.SelectByValue("php"); Assert.Equal("php", selectElement.SelectedOption.GetAttribute("value")); driver.Quit(); }
SelectByValue()
method takes a string
argument which is a value of the <option>
element.
Using XPath to Select a Dropdown Option Using Selenium
Apart from finding the element by id, we can also use an XPath
expression to find the element and the option:
[Fact] public void GivenTestInChrome_WhenDropdownElementIsSelectedByXPath_ThenOptionValueIsReturned() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://localhost:7006/"); var option = driver.FindElement( By.XPath("//select[@id='programming-language']/option[@value='typescript']")); string selectedOptionValue = option.GetAttribute("value"); Assert.Equal("typescript", selectedOptionValue); driver.Quit(); }
In this test, we select the desired options through one XPath
expression and assign it to the option. Since we already made our selection, there is no need to instantiate the SelectElement
class. We only get the value attribute of the selected option and use it in our assertion logic.
Differences Between Selenium WebDrivers in Selecting a Dropdown Option
Selenium supports all the major browsers along with some specific functionality for each one.
Now that we know how to use ChromeDriver
, let’s see if our tests need any modifications when we run them using GeckoDriver
and MSEdgeDriver
for Firefox and Edge (Chromium) browsers respectfully.
First, we will install additional Selenium.WebDriver.GeckoDriver
and Selenium.WebDriver.MSEdgeDriver
packages via NuGet Package Manager or the .NET CLI.
Next, we write our test for Selenium.WebDriver.GeckoDriver
:
[Fact] public void GivenTestInFirefox_WhenDropdownElementIsSelectedByText_ThenOptionValueIsReturned() { FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(); IWebDriver driver = new FirefoxDriver(service); driver.Navigate().GoToUrl("https://localhost:7006/"); var dropdown = driver.FindElement(By.Id("programming-language")); var selectElement = new SelectElement(dropdown); selectElement.SelectByText("Java"); Assert.Equal("java", selectElement.SelectedOption.GetAttribute("value")); driver.Quit(); }
Unlike the tests with ChromeDriver
, when we want to use GeckoDriver
, we first need to create FirefoxDriverService
instance with the default settings and then initialize the WebDriver. The rest of the test stays untouched.
Also, we use a similar approach with MSEdgeDriver
:
[Fact] public void GivenTestInEdge_WhenDropdownElementIsSelectedByText_ThenOptionValueIsReturned() { EdgeDriverService service = EdgeDriverService.CreateDefaultService(); IWebDriver driver = new EdgeDriver(service); driver.Navigate().GoToUrl("https://localhost:7006/"); var dropdown = driver.FindElement(By.Id("programming-language")); var selectElement = new SelectElement(dropdown); selectElement.SelectByText("Rust"); Assert.Equal("rust", selectElement.SelectedOption.GetAttribute("value")); driver.Quit(); }
From the tests, we can see there is no need to modify the existing code when testing with other major browsers with Selenium WebDriver except for the arrange part where we choose which driver to use and instantiate it.
Conclusion
Selenium enables us to select an option from the dropdown during UI testing of our web application with the help of WebDrivers. When we want to test our dropdown component with Selenium, we first need to initialize the WebDriver which allows us to navigate to the actual web page. Then, we can use methods to find our dropdown elements either by id or XPath expression. We can select elements by visible text, value, or index, and this is utilizing several methods on the SelectElement class.
Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!
Share:

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices.
© Copyright code-maze.com 2016 - 2023
Recommend
-
136
jest-webdriver - Connect Jest tests to Selenium WebDriver
-
72
本人用的是python3.63版本这里会讲到安装时所遇到的问题这里是根据火狐浏览器来操作的1、首先安装selenium在windows的cmd窗口通过pip没安装pip的小伙伴自行去搜搜相关pip安装方法pipinstallselenium安装成功后测试一下是否能正常运行打开百度输入关键字并且搜索fro...
-
15
Setting Http Proxy when using the selenium-webdriver gem and Firefox July 14, 2010 I've been using the selenium-webdriver ruby gem to do some automated...
-
13
Multi-select Dropdown List with Checkbox using jQuery Multiselect dropdown is very useful to allow the user to select multiple options in a selectbox. Multiple selections of the dropdown list can be added b...
-
6
Extract Text from PDF file using Selenium Webdriver in Scala Reading Time: < 1 minuteIf we want to verify PDF content d...
-
10
This tutorial will show you how to use react-select to create an async dropdown. I’m also utilising useState hooks to set and receive selected values, as well as Axios to retrieve data from the rest API. I have already...
-
42
How to solve captcha with selenium webdriver using python Well that quite easy, let's learn to solve captcha wi...
-
8
How To Handle Dropdowns In Selenium WebDriver Using Python?
-
10
-
13
How to Select Date From Datepicker in Selenium Webdriver Using Java ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK