Selenium Exceptions Example
1. Introduction
Selenium is used to automate browsers. Selenium WebDriver has found its place in test automation for web applications. It is used to create robust, browser-based regression automation suites and tests. It can be used for end to end testing of an application. This ensures that the application works as designed. Selenium supports various programming languages such as C#, Haskell, Java, Javascript, Python and Ruby through Selenium drivers. Selenium supports various browsers such as chrome, firefox, safari, opera and internet explorer.
2. Exceptions
In this section, We will take a look at some of the common exceptions which occur when running Selenium test cases. Broadly exceptions are divided into checked and unchecked exceptions.
Checked Exceptions are handled during compilation time itself. Unchecked exceptions are thrown at runtime and more catastrophic than the compile-time exception as it causes problems only during program execution.
In the coming subsections, We will take a look at the various exceptions which we can encounter in a selenium project. We will induce those exceptions either programmatically or manually.
2.1 NoSuchSessionException
We will first take a look at creating a selenium project to explore the various exceptions. Below is a example of gradle file which pulls the dependencies required for build of the project.
build.gradle
group 'com.jcg' version '1.0-SNAPSHOT' apply plugin: 'java' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile group: 'junit', name: 'junit', version: '4.12' compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.141.59' }
- Junit and Selenium are the only required dependencies for the project.
- ChromeDriver is needed as system dependency for the project. This is being set in the test class which will be described below.
SeleniumTest.java
package com.jcg.selenium; import org.junit.*; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class SeleniumTest { WebDriver webDriver; @BeforeClass public static void setUp() { System.setProperty("webdriver.chrome.driver", "chromedriver"); } @Before public void initializeDriver() { webDriver = new ChromeDriver(); } @After public void closeDriver() { webDriver.quit(); } @Test public void openGoogle() { webDriver.navigate().to("http://www.google.com"); Assert.assertEquals("Google", webDriver.getTitle()); } }
- In setup method, We provide the path to
ChromeDriver
via System property. - We use
@Before
and@After
method to initialize and close the driver. This will be run before and after each test case. - The actual test case of opening Google and checking the title is performed in the test case via method
openGoogle
.
In the above test case, if the actual session is closed before the test executes webdriver throws NoSuchSessionException
. We can introduce the error by closing the webdriver as below.
SeleniumTest.java
@Before public void initializeDriver() { webDriver = new ChromeDriver(); webDriver.close(); }
This code produces NoSuchSessionException
on executing the test case.
2.2 NoSuchElementException
This exception is thrown when the element webdriver is looking for is not visible in the web page. For example,consider the test case below
SeleniumTest.java
@Test public void googleTest1() { webDriver.navigate().to("http://www.google.com"); webDriver.findElement(By.id("unknown")); }
This code searches for an element with id unknown in google search page. When the element is not found, the application throws NoSuchElementException
.
2.3 WebDriverException
In this section, We will look at WebDriverException
which is thrown when the webdriver configuration has been incorrectly set. This is the most common error when webdriver has been configured incorrectly.
SeleniumTest.java
@Before public void initializeDriver() { ChromeOptions options = new ChromeOptions(); options.setCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR,"Yes"); webDriver = new ChromeDriver(options); }
- We are passing additional options to our
WebDriver
using chrome options. - We pass a capability type
UNHANDLED_PROMPT_BEHAVIOUR
which is typically associated with Internet Explorer. - We get
WebDriverException
with error message asinvalid argument: cannot parse capability: unhandledPromptBehavior
2.4 ElementNotVisibleException
This exception occurs when the element is rendered on the page but it is not visible to the webdriver for interaction. This can also happen when the webdriver is not able to uniquely identify the element we have provided for interaction.
SeleniumTest.java
@Test public void googleTest2() { webDriver.navigate().to("http://www.google.com"); webDriver.findElement(By.cssSelector("input[type=submit")).click(); }
- In this testcase, WebDriver searches for a input element with submit type to click.
- But Google homepage has two submit buttons and hence webdriver throws the exception.
- We can handle this by providing a unique css search term or xpath query.
2.5 InvalidElementStateException
This error occurs when the element is not in an interact-able state as needed by the WebDriver to perform the operation. We will consider a example by using a custom html page which has a disabled text box.
SeleniumTest.java
@Test public void googleTest3() throws MalformedURLException { webDriver.navigate().to(file); webDriver.findElement(By.cssSelector("input[value='hi'")).sendKeys("hi"); }
- In the example above, We navigate to the custom html page declared as constant in the class.
- We select the text element with value of hi using the css selector.
- We provide text to the textbox but webDriver would be unable to as the textbox is disabled. Hence we get the above exception.
2.6 ElementNotVisibleException
This exception occurs when the element located by the webdriver is hidden in the DOM for some reason. WebDriver on encountering such an element throws ElementNotVisibleException
.
SeleniumTest.java
@Test public void testCase5(){ webDriver.navigate().to(file); webDriver.findElement(By.cssSelector("input[value='hidden'")).sendKeys("hi"); }
- In this testcase, We find a hidden element using the css selector.
- Webdriver throws
ElementNotVisibleException
as the text element is not visible in the viewport.
2.7 UnhandledAlertException
This exception occurs when there is a presence of unknown alert. This can occur in many situations when an unexpected alert appears on the webpage. Any of the previous test cases can fail when we introduce an alert on the webpage. When we run the test case, We get the following error org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : hi}
. The way of resolving such issues is to dismiss the alert via test case if the alert is expected to appear.
SeleniumTest.java
@Test public void testCase6(){ webDriver.navigate().to(file); webDriver.switchTo().alert().dismiss(); String val = webDriver.findElement(By.id("attr")).getAttribute("custom"); }
- In the sample above, Test case is explicitly dismissing the alert. This ensures rest of the test case proceeds as expected.
2.8 NoAlertPresentException
This exception occurs when there is absence of alert and Selenium expects the presence of alert in the webpage. Considering the above testcase, if the webpage does not have an alert, WebDriver reports the absence of alert and fails with NoAlertPresentException
.
2.9 UnexpectedTagNameException
This exception occurs when the webdriver expects the presence of a particular tag but the actual tag is a different. We can illustrate with the below example.
SeleniumTest.java
@Test public void testCase7(){ webDriver.navigate().to(file); Select select = new Select(webDriver.findElement(By.id("attr"))); select.selectByIndex(0); }
- We are locating a text element but are expecting a Select element.
- WebDriver is unable to parse it as Select Element and hence throws
UnExpectedTagNameException
.
3. Selenium Exceptions – Summary
In this article, We covered the various exceptions which can occur in a selenium environment. These exceptions can be handled with an exception handler but at end of the day, tests fail to give us negative feedback. These serve as a feedback mechanism and ideally, the tests must be redesigned.
4. Download the Source code
You can download the full source code of this example here: Selenium Exceptions Example