Pytest Setup and Teardown for Selenium Testing

Instead of using setup_class and teardown_class, you can use setup_method and teardown_method to manage resources on an instance level. This means each test runs in complete isolation with its own browser instance, ensuring test independence and avoiding shared state issues.

import pytest
from selenium import webdriver

class TestClass:

    def setup_method(self):
        # Setup browser instance for each test
        self.browser = webdriver.Chrome()
    
    def test_buttons(self):
        # Use self.browser here to interact with the browser
        self.browser.get('http://example.com')
        assert self.browser.title == 'Example Domain'
    
    def test_buttons2(self):
        # Another test using its own browser instance
        self.browser.get('http://anotherexample.com')
        assert self.browser.title == 'Another Example'
    
    def teardown_method(self):
        # Teardown browser instance after each test
        if hasattr(self, 'browser'):
            self.browser.quit()

:white_check_mark: Why this works?

  • Each test runs in isolation, preventing state leakage.
  • If one test fails or crashes, it doesn’t affect others.
  • Ideal for independent, repeatable, and parallelized tests.