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

如何使用Selenium4自动驱动结合JUnit5(Java)捕获JavaScript错误?

Selenium4 捕获JS错误、全局配置及JUnit5测试报告存储方案

一、用Selenium4自带驱动捕获JavaScript错误

Selenium4的自动驱动管理不影响日志捕获逻辑,核心是通过浏览器选项配置日志偏好,再提取浏览器日志中的JS错误:

  1. 配置浏览器日志选项
    以Chrome为例,初始化ChromeOptions时指定日志捕获规则:

    ChromeOptions options = new ChromeOptions();
    LoggingPreferences logs = new LoggingPreferences();
    // 可设置Level.ALL捕获所有浏览器日志,或Level.SEVERE只抓严重错误
    logs.enable(LogType.BROWSER, Level.SEVERE);
    options.setCapability(CapabilityType.LOGGING_PREFS, logs);
    
    // Selenium4自动初始化驱动
    WebDriver driver = new ChromeDriver(options);
    
  2. 提取并筛选JS错误
    在测试执行完成后,获取浏览器日志并过滤出JS错误:

    LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
    for (LogEntry entry : logEntries) {
        // 通常JS错误消息包含"Uncaught"关键词,结合级别筛选
        if (entry.getMessage().contains("Uncaught") || entry.getLevel() == Level.SEVERE) {
            System.err.println("检测到JS错误: " + entry.getMessage());
            // 此处可将错误写入文件或临时存储,用于后续报告
        }
    }
    

二、全局应用JS错误捕获:自定义测试基类更高效

两种方式都可行,但自定义测试基类比单独用@AfterEach更适合全局统一配置:

方案1:自定义测试基类(推荐)

写一个基类,在初始化驱动时统一配置日志规则,在测试结束时自动捕获JS错误,所有测试类继承该基类即可:

public class BaseTest {
    protected WebDriver driver;

    @BeforeEach
    void setupDriver() {
        ChromeOptions options = new ChromeOptions();
        LoggingPreferences logs = new LoggingPreferences();
        logs.enable(LogType.BROWSER, Level.SEVERE);
        options.setCapability(CapabilityType.LOGGING_PREFS, logs);
        driver = new ChromeDriver(options);
    }

    @AfterEach
    void teardownAndCaptureJSErrors() {
        // 捕获并记录JS错误
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            if (entry.getMessage().contains("Uncaught")) {
                String testName = Thread.currentThread().getStackTrace()[2].getMethodName();
                System.err.println("测试[" + testName + "]出现JS错误: " + entry.getMessage());
            }
        }
        driver.quit();
    }
}

测试类直接继承使用:

class UserLoginTest extends BaseTest {
    @Test
    void testValidLogin() {
        driver.get("your-test-url");
        // 测试逻辑代码
    }
}

方案2:单独使用@AfterEach

如果不想用基类,也可以在每个测试类中编写@AfterEach方法,但需要重复配置日志规则,维护成本高,不适合全局场景。

三、JUnit5中存储测试报告的操作

JUnit5支持多种方式生成并存储测试报告,常用两种方案:

1. 通过构建工具生成内置报告

如果用Maven或Gradle,直接配置插件即可生成HTML/XML格式的报告:

  • Maven:在pom.xml中配置maven-surefire-plugin指定报告目录:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.2.5</version>
                <configuration>
                    <reportsDirectory>${project.build.directory}/junit-reports</reportsDirectory>
                </configuration>
            </plugin>
        </plugins>
    </build>
    

    执行mvn test后,报告会生成在target/junit-reports目录下。

  • Gradle:在build.gradle中配置报告输出:

    test {
        useJUnitPlatform()
        reports {
            html.required = true
            html.outputLocation = file("$buildDir/reports/junit/html")
            xml.required = true
        }
    }
    

2. 自定义扩展将JS错误写入报告

要把捕获的JS错误附加到测试报告中,可实现JUnit5的TestWatcher扩展:

public class JSErrorReportExtension implements TestWatcher {
    private WebDriver driver;

    public JSErrorReportExtension(WebDriver driver) {
        this.driver = driver;
    }

    @Override
    public void testFailed(ExtensionContext context, Throwable cause) {
        recordJSErrors(context);
    }

    @Override
    public void testSuccessful(ExtensionContext context) {
        // 测试成功也可检查JS错误
        recordJSErrors(context);
    }

    private void recordJSErrors(ExtensionContext context) {
        LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            if (entry.getMessage().contains("Uncaught")) {
                // 将错误附加到测试报告的附加信息中
                context.publishReportEntry("JS错误详情", entry.getMessage());
            }
        }
    }
}

在测试类中注册扩展并传入驱动实例:

@ExtendWith(JSErrorReportExtension.class)
class ProductTest {
    private WebDriver driver;

    @BeforeEach
    void setup() {
        ChromeOptions options = new ChromeOptions();
        LoggingPreferences logs = new LoggingPreferences();
        logs.enable(LogType.BROWSER, Level.SEVERE);
        options.setCapability(CapabilityType.LOGGING_PREFS, logs);
        driver = new ChromeDriver(options);
        // 将驱动存入扩展上下文供扩展使用
        ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(getClass());
        context.getStore(namespace).put("driver", driver);
    }
}

这样JS错误会被纳入JUnit5的HTML报告,在"Additional Information"板块展示。

内容的提问来源于stack exchange,提问作者Kadir Ky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:27:44