Python unittest - UI Testing
By ski11up.com
Python unittest comes default with standard python
installation. It has a few advantages like we can use setUp
, tearDown
and assertsXXXX
.
Test Class
We have to do a few things in our test class to make it suitable for unittest
.
-
import unittest
-
inherit the
unittest.TestCase
-
add
__name__ ..
at the bottom of the test class
In case if you recently started on python
, you may want to check the previous blogs on VSCode for Python for installing and setting up VSCode
for Python
and creating your first python project.
Project Structure
Below is the project directory structure.

Tests are residing inside the tests
directory.
Relative import of modules are deprecated in python3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import unittest (1)
from selenium import webdriver
from pages.google_landing_page import GoogleLandingPage
class TestGoogleSearch(unittest.TestCase): (2)
def setUp(self): (3)
print('setting up browser...')
self.browser = webdriver.Chrome()
self.glp = GoogleLandingPage(driver=self.browser)
def test_google_search(self): (4)
self.glp.go()
self.glp.get_search_box().text_input('covid19')
self.glp.get_search_button().click()
def tearDown(self): (5)
print('cleaning up browser...')
self.browser.close()
if __name__ == '__main__': (6)
unittest.main()
1 | importing the required module, this is required for unittest |
2 | this is required, inherit the TestCase class |
3 | unittest comes with setUp , tearDown , setUpClass , tearDownClass etc.. this allows us to execute statements before the actual test and after test execution is completed |
4 | this is actual test method, note that it starts with test_ |
5 | same as point 3 |
6 | this will load the tests from the module and execute it |
Take a look at self keywork in the above code snipped, it is referring the TestClass itself |
Execute Python unittest
Open a terminal window inside VSCode
→ Terminal → New Terminal and executes the below command.
Always good to use the inbuild Editor Terminal for productivity reasons |
$ python3 -m unittest tests.test_google_search.TestGoogleSearch
This test script will open the chrome
browser and enter covid19
and click on the search button and show the search result and close the browser.

Look at the test command it has the name of the test module which is tests
followed by the test method name and then the class name, this is required as per the standard instructions of `python unittest.
unittest requires fully qualified TestClass name |
Source Code
You can either git fork
, git clone
or download this repository
py-unittest-ui-tests.