0
0
Selenium Pythontesting~7 mins

Test functions and classes in Selenium Python

Choose your learning style9 modes available
Introduction

Test functions and classes help organize your checks so you can find and fix problems easily.

When you want to check if a website button works correctly.
When you need to test multiple parts of a web page separately.
When you want to run the same test steps many times with different data.
When you want to keep your tests neat and easy to understand.
When you want to share setup steps like opening a browser for many tests.
Syntax
Selenium Python
import unittest

class TestExample(unittest.TestCase):
    def setUp(self):
        # Runs before each test
        pass

    def test_something(self):
        # Your test code here
        self.assertEqual(1, 1)

    def tearDown(self):
        # Runs after each test
        pass

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

Use setUp to prepare things before each test.

Use tearDown to clean up after each test.

Examples
A simple test function without a class using plain assert.
Selenium Python
def test_addition():
    assert 2 + 2 == 4
A test class with one test method using unittest assertions.
Selenium Python
import unittest

class TestMath(unittest.TestCase):
    def test_subtraction(self):
        self.assertEqual(5 - 3, 2)
A Selenium test class opening a browser, checking the title, then closing the browser.
Selenium Python
import unittest

class TestBrowser(unittest.TestCase):
    def setUp(self):
        from selenium import webdriver
        self.driver = webdriver.Chrome()

    def test_title(self):
        self.driver.get('https://example.com')
        self.assertIn('Example', self.driver.title)

    def tearDown(self):
        self.driver.quit()
Sample Program

This test opens the Chrome browser, goes to example.com, checks the page title contains 'Example Domain', then closes the browser.

Selenium Python
import unittest
from selenium import webdriver

class TestExampleDotCom(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()

    def test_title_contains_example(self):
        self.driver.get('https://example.com')
        self.assertIn('Example Domain', self.driver.title)

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
OutputSuccess
Important Notes

Always close the browser in tearDown to avoid leftover windows.

Use descriptive test method names starting with test_ so the test runner finds them.

Test classes help group related tests and share setup code.

Summary

Test functions and classes organize your checks clearly.

Use setUp and tearDown to prepare and clean up.

Run tests with unittest.main() to see results easily.