Selenium – Multiple Test in Python Class

By | 09/07/2015

A Python Unittest Class consist of 3 basic functions.

def setUp(self): => it is first function running before test cases. generally, define Class-wide objects/variables such as drvier, timeout settings etc..

def test_xxx(self): => it is test case function that to be running. test case functions in unittest shoud start with “test_

def tearDown(self): => it is running after each test case function to clean/destroy variables. for ex: driver.close()

as you can see, to write a test case, you should define a function start with “test_”. in one class, you can define more than one function. Generally, for each module to be tested, define all in same class.

you can see following code, there are 2 test cases and one will be passed and one will be failed. you can see from their name which one is.

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

class TestClass(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(20)
        self.driver.set_page_load_timeout(20)
        self.driver.maximize_window()
    
    def test_MahsumAkbasNet_Pass(self):
        self.driver.get("http://www.mahsumakbas.net")
        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 test_MahsumAkbasNet_Fail(self):
        self.driver.get("http://www.mahsumakbas.net")
        headerTitle = self.driver.find_element_by_xpath("//a[@class='site-description']").text
        
        self.assertEqual(headerTitle, "Lorem ipsum dolor sit amet", "Title is wrong")
    
    def tearDown(self):
        self.driver.close()

if __name__ == '__main__':
    unittest.main()

output will be:

F.
======================================================================
FAIL: test_MahsumAkbasNet_Fail (__main__.TestClass)
———————————————————————-
Traceback (most recent call last):
File “D:\xxx\src\unittestpackage\mahsumakbasnetUnittest.py”, line 23, in test_MahsumAkbasNet_Fail
self.assertEqual(headerTitle, “Lorem ipsum dolor sit amet”, “Title is wrong”)
AssertionError: Title is wrong

———————————————————————-
Ran 2 tests in 23.497s

FAILED (failures=1)

first line of output F. mean, there is two test case. “F” is “FAILED”.  The dot(.) sign mean, one is PASSED

Leave a Reply

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

*