0
0
Selenium-pythonHow-ToBeginner · 4 min read

How to Use Selenium with unittest in Python for Web Testing

Use unittest.TestCase to create test classes and methods, and initialize Selenium WebDriver in setUp. Write test steps inside methods starting with test_, and close the browser in tearDown. Run tests with unittest.main() to get pass/fail results.
📐

Syntax

Use unittest.TestCase as the base class for your test class. Define setUp to start the Selenium WebDriver before each test. Write test methods starting with test_ to perform actions and assertions. Use tearDown to quit the browser after each test.

  • setUp: Prepare test environment (open browser).
  • test_method: Contains test steps and assertions.
  • tearDown: Clean up (close browser).
python
import unittest
from selenium import webdriver

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

    def test_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()
💻

Example

This example opens the Chrome browser, navigates to example.com, checks the page title contains 'Example Domain', and then closes the browser. It shows how to combine Selenium with unittest for automated testing.

python
import unittest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

class ExampleDotComTest(unittest.TestCase):
    def setUp(self):
        options = Options()
        options.add_argument('--headless')  # Run browser in headless mode
        service = Service()
        self.driver = webdriver.Chrome(service=service, options=options)

    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()
Output
... ---------------------------------------------------------------------- Ran 1 test in 2.345s OK
⚠️

Common Pitfalls

  • Not quitting the browser in tearDown causes leftover browser processes.
  • Forgetting to prefix test methods with test_ means unittest won't run them.
  • Not using assertions inside test methods results in tests that don't verify anything.
  • Running WebDriver without proper driver executable setup causes errors.

Always ensure your WebDriver executable (like chromedriver) is in PATH or specify its location.

python
import unittest
from selenium import webdriver

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

    def example(self):  # Missing 'test_' prefix, won't run
        self.driver.get('https://example.com')
        # No assertion here

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

# Corrected version:
class GoodTest(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()

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

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

Quick Reference

StepPurposeExample Code Snippet
Import unittest and seleniumPrepare testing framework and browser controlimport unittest from selenium import webdriver
Create test classGroup related testsclass MyTest(unittest.TestCase):
Define setUpStart browser before each testdef setUp(self): self.driver = webdriver.Chrome()
Write test methodsPerform actions and assertionsdef test_title(self): self.driver.get('https://example.com') self.assertIn('Example Domain', self.driver.title)
Define tearDownClose browser after each testdef tearDown(self): self.driver.quit()
Run testsExecute all tests in the fileif __name__ == '__main__': unittest.main()

Key Takeaways

Use unittest.TestCase with setUp and tearDown to manage Selenium WebDriver lifecycle.
Prefix test methods with 'test_' so unittest can discover and run them.
Always include assertions to verify expected outcomes in your tests.
Quit the browser in tearDown to avoid leftover processes.
Ensure WebDriver executables are correctly installed and accessible.