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

TestNG中多类测试用例无法在单个浏览器实例运行的问题

问题:多TestNG测试类复用同一ChromeDriver实例失败

我在运行多个分属不同类的测试用例时,发现执行到最后一个类时会新建ChromeDriver实例,所有操作重新开始。希望所有测试类都复用同一个浏览器实例执行。目前代码无报错,但达不到预期效果,之前尝试过其他方法还出现过“无法实例化Second类”等错误。


主类(Main Class)

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeClass;

public class Main1 {
    
    public static WebDriver driver;
    public static WebDriverWait w;
    
    @BeforeClass
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Person\\Downloads\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }

}

第二个类(Second Class)

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;

public class Second extends Main{
    
    @BeforeClass
    public void openWebsite() {
        driver.get("http://www.example.com");
        System.out.println("Verfying Title...");
        String expTitle = "Company Title";
        String actualTitle = driver.getTitle();
        if (expTitle.equals(actualTitle)) {
            System.out.println("Title Verified");
        } else {
            System.out.println("Title Not Verified");
        }
    }
    
    @Test(priority=1)
    public void companyCode() {
        
        w = new WebDriverWait(driver, Duration.ofSeconds(30));

        //Dropdown to select company

    }
    
    @Test(priority=2)
    public void reload() {
        
        w = new WebDriverWait(driver, Duration.ofSeconds(2));
        
        
        //Click another tab on the application and click reload
    
    @Test(priority=3)
    public void orgtree() {

        By by = By.xpath("//span[normalize-space()='node']//preceding-sibling::div[2]");
        retryingFindClick(driver, by);  //Click Expand node

        //clicking on elements on the website
        
    }
    
    public boolean retryingFindClick(WebDriver driver, By by) {
        boolean result = false;
        int attempts = 0;
        while(attempts < 5) {
            try {
                driver.findElement(by).click();
                result = true;
                break;
            } catch(Exception e) {
            }
            attempts++;
        }
        return result;
    }

}

最后一个类(Last Class)

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;

public class Last extends Main {
    
    @Test
    public void Window1() {
        
        w = new WebDriverWait(driver, Duration.ofSeconds(2));
        
        //Click on a window on the website
        
        
    }

}

TestNG XML配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">


<suite name="TestSuite1">
  <test thread-count="5" name="Test1">
    
    <classes>
        <class name="test.Main"/>
        <class name="test.Second"/>
        <class name="test.Last"/>
    </classes>
    
    
  </test> <!-- Test1 -->
</suite> <!-- TestSuite1 -->

问题根源

  1. TestNG默认会为每个测试类创建独立实例,父类的@BeforeClass会被每个子类触发,导致多次初始化Driver。
  2. XML中单独配置了test.Main类,会提前执行一次Driver初始化,后续子类继承时又重复触发初始化逻辑。
  3. 存在类名拼写错误:主类是Main1,但子类继承的是Main,会引发运行异常。
  4. Second类中reload()方法缺少闭合括号,存在语法错误。

修复方案

1. 修正类继承与初始化逻辑

将父类的@BeforeClass改为@BeforeTest,确保整个测试只初始化一次Driver,同时增加判重避免重复创建:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;

public class Main {
    public static WebDriver driver;
    public static WebDriverWait w;

    @BeforeTest
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Person\\Downloads\\chromedriver_win32\\chromedriver.exe");
        if (driver == null) {
            driver = new ChromeDriver();
            driver.manage().window().maximize();
        }
    }
}

2. 修复Second类语法错误

给reload()方法补上闭合括号,并确保继承正确的父类:

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class Second extends Main {
    
    @BeforeClass
    public void openWebsite() {
        driver.get("http://www.example.com");
        System.out.println("Verifying Title...");
        String expTitle = "Company Title";
        String actualTitle = driver.getTitle();
        if (expTitle.equals(actualTitle)) {
            System.out.println("Title Verified");
        } else {
            System.out.println("Title Not Verified");
        }
    }
    
    @Test(priority=1)
    public void companyCode() {
        w = new WebDriverWait(driver, Duration.ofSeconds(30));
        // Dropdown to select company
    }
    
    @Test(priority=2)
    public void reload() {
        w = new WebDriverWait(driver, Duration.ofSeconds(2));
        // Click another tab on the application and click reload
    } // 补上缺失的闭合括号
    
    @Test(priority=3)
    public void orgtree() {
        By by = By.xpath("//span[normalize-space()='node']//preceding-sibling::div[2]");
        retryingFindClick(driver, by);  // Click Expand node
        // clicking on elements on the website
    }
    
    public boolean retryingFindClick(WebDriver driver, By by) {
        boolean result = false;
        int attempts = 0;
        while(attempts < 5) {
            try {
                driver.findElement(by).click();
                result = true;
                break;
            } catch(Exception e) {
            }
            attempts++;
        }
        return result;
    }
}

3. 调整Last类的执行依赖

通过dependsOnGroups确保Last类测试在Second类所有测试完成后执行:

import java.time.Duration;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class Last extends Main {
    
    @Test(dependsOnGroups = "secondTests")
    public void Window1() {
        w = new WebDriverWait(driver, Duration.ofSeconds(2));
        // Click on a window on the website
    }
}

4. 更新TestNG XML配置

移除单独的test.Main类,设置单线程避免Driver冲突,并定义测试组:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">

<suite name="TestSuite1">
  <test thread-count="1" name="Test1">
    <groups>
      <define name="secondTests">
        <include name="companyCode"/>
        <include name="reload"/>
        <include name="orgtree"/>
      </define>
    </groups>
    
    <classes>
        <class name="test.Second"/>
        <class name="test.Last"/>
    </classes>
  </test> <!-- Test1 -->
</suite> <!-- TestSuite1 -->

内容的提问来源于stack exchange,提问作者kunal kaklij

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:50:39