Wednesday, July 29, 2015

Selenium : How to retrieve text from a Textbox in Selenium WebDriver using C#

Sometimes we need to retrieved data in a form for edit and for this we search data by using a search keyword. For example, we need to edit employee personal information and in that case we need to search the Employee information using Employee ID. All the data are displayed in a text box and we verify that proper data is displayed in the textbox for this employee id. Selenium WebDriver uses different method to retrieve data from textbox for assertion.

Selenium WebDriver has GetAttribute() method to capture textbox data.   

image

Common syntax to use this command,

ElementName.GetAttribute(“value”);

Here “value” is the argument and it returns the value of the attribute of that element. 

For example in C#,

image

Lets do a short project on how we can implement in our test scenario. For example we have the following page where we have to verify the data displayed at FirstName and LastName field. 

Page link : http://demos.telerik.com/aspnet-ajax/grid/examples/data-editing/form-template-update/defaultcs.aspx

image

Step 1 : Open Visual Studio and create a new unit test project.

image

Step 2 : Add a reference for WebDriver from Nuget package manager. How to add a reference from Nuget package can be found in my another post.

image

Step 3 : Write the following code for opening page using Firefox Browser  TestMethod1().

image

Note that we need to add following namespaces for webdriver.

image

Step 4 : Write the code for getting First name and last name from textboxes.

image

Note that we use GetAttribute("value") method here that returns the text displayed on that element and this element is a textbox.

Step 5 : Write the code for verification. 

image

Step 6 :  Now close the driver. The TestMethod1() will be,

image

Step 7 : Now build the application by going to Build > Build Solution and go to test explorer and run the application by right clicking on the test name and click on Run Selected Tests.

image 

Test will run and it capture the value from textbox and verify expected value.

image

Happy scripting with Selenium WebDriver…!!!