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

执行Gradle TestNG分组测试命令时出现空指针异常求助

问题:执行Gradle测试命令时触发空指针异常

执行命令 gradle clean test -P testGroups="test" 运行test分组的测试时,出现空指针异常,报错信息如下:

FAILED: BotAttributesTest
java.lang.NullPointerException
    at sanityTests.BotAttributesTest.BotAttributesTest(BotAttributesTest.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

问题出在logger相关代码行,相关代码声明及实现如下:

public ExtentSparkReporter htmlReporter;
public static ExtentReports extent;
public ExtentTest logger;
public static WebDriver wd;

@BeforeMethod
public void logger(Method testMethod){
    logger = extent.createTest(testMethod.getName());

    WebDriverManager.chromedriver().setup();
}
解决方案

空指针异常的直接原因是extent变量未初始化就被调用。你仅声明了public static ExtentReports extent;,但未在调用extent.createTest()前完成初始化操作。

具体解决步骤:

  • 在@BeforeMethod执行前初始化extent实例,推荐使用@BeforeClass注解的静态方法完成配置:
@BeforeClass
public static void setupExtent() {
    // 初始化HTML报告器,指定报告输出路径
    htmlReporter = new ExtentSparkReporter("test-output/extent-report.html");
    // 初始化ExtentReports并关联报告器
    extent = new ExtentReports();
    extent.attachReporter(htmlReporter);
}
  • 注意测试类的构造方法BotAttributesTest(报错行29)会在@BeforeMethod之前执行,如果构造方法中也用到了logger或extent,必须确保这些变量在构造方法执行前已初始化——将extent的初始化放在@BeforeClass(类加载时执行)或静态代码块中可以避免这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:10:21