It doesn’t take long when using Selenium before you run into errors from Selenium that may seem inexplicable (e.g., NoSuchElementException
or StaleElementReferenceException
). They can be a bit of a shock if you’re not sure what they are, how to handle them, or where to find documentation on how to address them.
By adding some simple exception handling we can catch Selenium’s errors and make our tests more resilient.
Let’s take a look at an example.
Example
For this example we’ll use a login example from the-internet.
Java
//ExceptionTest.java
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
public class ExceptionTest {
WebDriver driver;
@BeforeTest
public void beforeTest() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(http://the-internet.herokuapp.com/login);
}
//Without exception handing
@Test
public void test1() {
driver.findElement(By.id("username")).sendKeys("tomsmith");
driver.findElement(By.id("password")).sendKeys("SuperSecretPassword!");
driver.findElement(By.id("login")).submit();
Assert.assertEquals( driver.findElement(By.id("login")).isDisplayed(),true);
}
//With exception handing
@Test
public void test2() {
driver.get(http://the-internet.herokuapp.com/login);
driver.findElement(By.id("username")).sendKeys("tomsmith");
driver.findElement(By.id("password")).sendKeys("SuperSecretPassword!");
driver.findElement(By.id("login")).submit();
try {
Assert.assertEquals( driver.findElement(By.id("login")).isDisplayed(),true);
}
catch (NoSuchElementException e)
{
e.printStackTrace();
}
}
@AfterTest
public void afterTest() {
driver.quit();
}
}
Python
# filename: exception_handling.py
import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
class exception_handling(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def tearDown(self):
self.driver.quit()
def test_example_1(self):
driver = self.driver
driver.get('http://the-internet.herokuapp.com/lohin')
driver.find_element_by_id('username').send_keys('tomsmith')
driver.find_element_by_id('password').send_keys('SuperSecretPassword!')
driver.find_element_by_id('login').click()
self.assertEqual(driver.find_element_by_id('login').is_displayed(),True,'')
def test_example_2(self):
driver = self.driver
driver.get('http://the-internet.herokuapp.com/lohin')
driver.find_element_by_id('username').send_keys('tomsmith')
driver.find_element_by_id('password').send_keys('SuperSecretPassword!')
driver.find_element_by_id('login').click()
try:
self.assertEqual(driver.find_element_by_id('login').is_displayed(),True,'')
except NoSuchElementException:
print('Element Not found')
if __name__ == "__main__":
unittest.main()
Ruby
# filename: exception_handling.rb
require 'selenium-webdriver'
require 'rspec/expectations'
include RSpec::Matchers
def setup
@driver = Selenium::WebDriver.for :firefox
end
def teardown
@driver.quit
end
def run
setup
yield
teardown
end
#without exception handling
run do
@driver.get 'http://the-internet.herokuapp.com/login'
@driver.find_element(id: 'username').send_keys('tomsmith')
@driver.find_element(id: 'password').send_keys('SuperSecretPassword!')
@driver.find_element(id: 'login').submit
expect(@driver.find_element(id: 'login').displayed?).to eql false
end
#with exception handling
run do
@driver.get 'http://the-internet.herokuapp.com/login'
@driver.find_element(id: 'username').send_keys('tomsmith')
@driver.find_element(id: 'password').send_keys('SuperSecretPassword!')
@driver.find_element(id: 'login').submit
begin
expect(@driver.find_element(id: 'login').displayed?).to eql false
rescue Selenium::WebDriver::Error::NoSuchElementError
false
rescue Selenium::WebDriver::Error::StaleElementReferenceError
false
end
end
C#
// filename: ExceptionHanding.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Collections.Generic;
using System;
public class ExceptionHanding
{
IWebDriver Driver;
[SetUp]
public void SetUp()
{
Driver = new FirefoxDriver();
}
[TearDown]
public void TearDown()
{
Driver.Quit();
}
//without exception handling
[Test]
public void Example1()
{
Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/login");
Driver.FindElement(By.Id("username")).SendKeys("tomsmith");
Driver.FindElement(By.Id("password")).SendKeys("SuperSecretPassword!");
Driver.FindElement(By.Id("login")).Submit();
Assert.True(Driver.FindElement(By.Id("login")).Displayed);
}
//with exception handling
[Test]
public void Example2()
{
Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/login");
Driver.FindElement(By.Id("username")).SendKeys("tomsmith");
Driver.FindElement(By.Id("password")).SendKeys("SuperSecretPassword!");
Driver.FindElement(By.Id("login")).Submit();
try{
Assert.True(Driver.FindElement(By.Id("login")).Displayed);
}
catch(NoSuchElementException e)
{
Console.WriteLine("Element not displayed")
}
}
}
If you save the file and run it here is what will happen:
- Open the browser
- Visit the page
- Log in
- Check to see that the login form is NOT displayed
- Catch the exception from Selenium and return
false
instead - Complete the assertion using the boolean response (e.g.,
false
) - Close the browser