You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何演示TestNG及TestNG+Selenium中多生命周期注解的实时示例

Got it, let's break this down with clear, runnable examples so you can see exactly how these TestNG annotations work—both on their own and paired with Selenium. I'll start with a pure TestNG demo to lay the groundwork, then move to the Selenium integration since that's where these annotations really shine in real-world test automation.

1. Pure TestNG Annotation Example

First, let's cover the core annotations you asked about: @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest, @BeforeClass, @AfterClass. Here's a complete test class that demonstrates their execution order:

import org.testng.annotations.*;

public class PureTestNGAnnotationDemo {

    // Runs ONCE before all tests in the entire suite
    @BeforeSuite
    public void beforeSuite() {
        System.out.println("🔹 Executing BeforeSuite: Setting up suite-level resources (e.g., global config)");
    }

    // Runs ONCE after all tests in the entire suite
    @AfterSuite
    public void afterSuite() {
        System.out.println("🔹 Executing AfterSuite: Cleaning up suite-level resources");
    }

    // Runs ONCE before all test methods under the <test> tag in testng.xml
    @BeforeTest
    public void beforeTest() {
        System.out.println("🔸 Executing BeforeTest: Preparing test data for all methods in this test group");
    }

    // Runs ONCE after all test methods under the <test> tag in testng.xml
    @AfterTest
    public void afterTest() {
        System.out.println("🔸 Executing AfterTest: Cleaning up test data for this test group");
    }

    // Runs ONCE before any test methods in this class are executed
    @BeforeClass
    public void beforeClass() {
        System.out.println("🔶 Executing BeforeClass: Initializing class-level objects");
    }

    // Runs ONCE after all test methods in this class are executed
    @AfterClass
    public void afterClass() {
        System.out.println("🔶 Executing AfterClass: Destroying class-level objects");
    }

    // Test method 1
    @Test
    public void testMethodOne() {
        System.out.println("✅ Executing Test Method 1");
    }

    // Test method 2
    @Test
    public void testMethodTwo() {
        System.out.println("✅ Executing Test Method 2");
    }
}

Expected Execution Output:

When you run this class (or via a TestNG suite XML), you'll see this order:

🔹 Executing BeforeSuite: Setting up suite-level resources (e.g., global config)
🔸 Executing BeforeTest: Preparing test data for all methods in this test group
🔶 Executing BeforeClass: Initializing class-level objects
✅ Executing Test Method 1
✅ Executing Test Method 2
🔶 Executing AfterClass: Destroying class-level objects
🔸 Executing AfterTest: Cleaning up test data for this test group
🔹 Executing AfterSuite: Cleaning up suite-level resources

2. TestNG + Selenium Annotation Example

Now let's add @BeforeMethod and @AfterMethod to the mix—these are super useful in Selenium tests because they let you run setup/teardown logic before and after every individual test method (like resetting the browser state).

In this example, we'll automate a simple flow on Google Search:

  • @BeforeSuite: Set up global Selenium config (e.g., configure Chrome options)
  • @BeforeTest: Prepare search keywords
  • @BeforeClass: Initialize the WebDriver instance (once per class)
  • @BeforeMethod: Navigate to Google homepage before each test
  • Test methods: Perform different search queries
  • @AfterMethod: Clear the search box after each test
  • @AfterClass: Quit the WebDriver instance
  • @AfterSuite: Clean up any leftover resources

Here's the code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.*;

public class TestNGSeleniumDemo {

    private WebDriver driver;
    private String[] searchKeywords;

    @BeforeSuite
    public void beforeSuite() {
        // Configure Chrome options (e.g., maximize window)
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        System.setProperty("webdriver.chrome.driver", "path/to/your/chromedriver");
        System.out.println("🔹 BeforeSuite: Configured Chrome options");
    }

    @AfterSuite
    public void afterSuite() {
        // Clean up any global resources (e.g., screenshot folders)
        System.out.println("🔹 AfterSuite: Cleaned up suite-level resources");
    }

    @BeforeTest
    public void beforeTest() {
        // Prepare test data (search keywords)
        searchKeywords = new String[]{"TestNG Annotations", "Selenium WebDriver"};
        System.out.println("🔸 BeforeTest: Loaded search keywords");
    }

    @AfterTest
    public void afterTest() {
        // Clear test data to free memory
        searchKeywords = null;
        System.out.println("🔸 AfterTest: Cleared search keywords");
    }

    @BeforeClass
    public void beforeClass() {
        // Initialize WebDriver once per class to save time
        driver = new ChromeDriver();
        System.out.println("🔶 BeforeClass: Launched Chrome browser");
    }

    @AfterClass
    public void afterClass() {
        // Quit WebDriver to avoid hanging browser instances
        if (driver != null) {
            driver.quit();
            System.out.println("🔶 AfterClass: Closed Chrome browser");
        }
    }

    @BeforeMethod
    public void beforeMethod() {
        // Navigate to Google homepage to ensure a fresh state for each test
        driver.get("https://www.google.com");
        System.out.println("🔷 BeforeMethod: Navigated to Google homepage");
    }

    @AfterMethod
    public void afterMethod() {
        // Clear the search box to reset state for the next test
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.clear();
        System.out.println("🔷 AfterMethod: Cleared search box");
    }

    @Test
    public void testSearchFirstKeyword() {
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys(searchKeywords[0]);
        searchBox.submit();
        System.out.println("✅ Test 1: Searched for '" + searchKeywords[0] + "'");
    }

    @Test
    public void testSearchSecondKeyword() {
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys(searchKeywords[1]);
        searchBox.submit();
        System.out.println("✅ Test 2: Searched for '" + searchKeywords[1] + "'");
    }
}

Key Notes for This Example:

  • @BeforeClass: We initialize the WebDriver once here instead of in @BeforeMethod to avoid launching a new browser for every test—this speeds up execution.
  • @BeforeMethod: Ensures we start on the Google homepage for every test, so the outcome of one test doesn't affect the next.
  • @AfterMethod: Clears the search box to reset the state before the next test runs, keeping tests independent.
  • All annotations follow the same execution order as the pure TestNG example, with @BeforeMethod running before each test and @AfterMethod running after each test.

内容的提问来源于stack exchange,提问作者Akash Dutta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:13:27