Home » Selenium WebDriver Handling Checkbox

Selenium WebDriver Handling Checkbox

by Online Tutorials Library

Handling Checkbox

In this section, you will learn how to handle checkbox in selenium webdriver.

Let’s create a test case in which we will automate the following scenarios:

  • Invoke a Google chrome browser.
  • Navigate to the website in which you handle the checkbox.
  • Select the ‘Senior Citizen‘ checkbox from the spicejet website.
  • Close the driver.

Now, we will create a test case step by step in order to provide you proper understanding of how to handle checkbox.

Step 1: Launch the Eclipse IDE.

Step 2: Right click on the src folder and then click on the New > class.

Handling Checkbox

  • Enter the class name. I provide the class name as Checkbox_test.

Handling Checkbox

Step 3: Now, we will invoke the Google Chrome browser. We will download the chromedriver.exe file and set the system property to the path of your chromedriver.exe file.

Here is the sample code to set the system property to the path of a chromedriver.exe file.

Here is the sample code to invoke the Google chrome browser.

Combining both of the above code blocks, we will get the code snippet to launch Google chrome browser.

Step 4: We are done with the first test case, i.e., invoking a Google chrome browser. Now we will write the code to automate the test case. Our second test case is to navigate to the “spicejet” website.

Here is the sample code to navigate to the “spicejet” website.

Here is the complete code:

Step 5: Now we try to locate the ‘Senior Citizen’ checkbox by inspecting its HTML code.

Handling Checkbox

Note the id attribute of a checkbox.

Handling Checkbox

In the above case, we observe that ‘id’ is a unique attribute, so we locate the checkbox by using an id attribute.

Step 6: To automate the third test case, we need to write the code that will locate ‘Senior Citizen‘ checkbox.

Here is the code that will handle the “Senior Citizen” checkbox.

In the above code, we haven’t used the complete ‘id’ attribute value as it is very big. I have used the half part of the ‘Senior Citizen’ checkbox, and other half part is represented in the form of regular expression, i.e., ‘*=’.

We have used two methods in the above code:

  • isSelected(): This method determines whether the checkbox is selected or not. If the checkbox is selected, then this method returns true otherwise false.
  • click(): This method selects the locator. In this case, it is selecting the “Senior Citizen” checkbox.

Output

Handling Checkbox

Output on the Console

Handling Checkbox

Next TopicAssertions

You may also like