Selenium + Java · Lesson 37 of 44

0/44 done

Module 37: Test Lifecycle

37. Test Lifecycle Management & Session Teardown

15 minlesson

Your task

Implement executeWithLifecycle:

  1. Accept Supplier<WebDriver> driverFactory and Consumer<WebDriver> testAction.
  2. Initialize driver, execute testAction inside try, and in finally block call driver.quit().

Write it in the editor, then press Check answer (Ctrl + Enter).

Standard BaseTest Lifecycle

java
public class BaseTest {
    protected WebDriver driver;

    public void setUp() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless=new");
        driver = new ChromeDriver(options);
        driver.manage().window().maximize();
    }

    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Key Takeaways & Walkthrough Summary

Managing WebDriver lifecycles properly guarantees that crashed tests do not leave abandoned browser processes consuming CPU and memory. In this lesson, you will structure clean BaseTest classes with setup and teardown guarantees. Let's master the test lifecycle!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why should driver.quit() always be placed in a finally block?

If an assertion fails or an exception occurs during the test, a finally block guarantees the browser process is still cleanly closed.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip