Selenium – Assertion with Python Unittest

By | 20/06/2015

in a previous post, i shared a basic script to use Python Unittest. At that post, there is not any Assertion(verification). Now, let’s see power of Assertions.

after we prepare our test and its steps, we will need at some point to check results. in following example, get header title and compare it if it correct or not. there is assertEqual function in Python Unittest.

assertEqual(first, second, msg) => first and second are vakues to be compared. msg is a message to be printed if function is failed. This function compare two values, if they are equal result will be pass, but if they are not some result will be failed.
we will find following text in html code in our website: <a class=”site-description”>A Blog For Software Testing and Automation</a>


# -*- coding: UTF-8 -*-
import unittest
from selenium import webdriver

class TestClass(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
    def test_MahsumAkbasNet_Pass(self):
        headerTitle = self.driver.find_element_by_xpath("//a[@class='site-description']").text
        self.assertEqual(headerTitle, "A Blog For Software Testing and Automation", "Title is wrong")
    def tearDown(self):

if __name__ == '__main__':

when run as python script in Eclipse, you will see following output:

Ran 1 test in 11.248s


let’s see a failed example. in same code change function as:

self.assertEqual(headerTitle, "Lorem ipsum dolor sit amet", "Title is wrong")

output will be:

FAIL: test_MahsumAkbasNet_Pass (__main__.TestClass)
Traceback (most recent call last):
  File "D:\xxx\src\unittestpackage\", line 17, in test_MahsumAkbasNet_Pass
    self.assertEqual(headerTitle, "Lorem ipsum dolor sit amet", "Title is wrong")
AssertionError: Title is wrong

Ran 1 test in 12.956s

FAILED (failures=1)

Have nice testing !!!

Leave a Reply

Your email address will not be published. Required fields are marked *