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

单文件多Cucumber Feature场景运行时出现NullPointerException问题

解决Cucumber测试中clickOnAddStudentButton方法的NullPointerException问题

问题现象

第一个Manage Students page Scenario执行完全正常,但第二个Create Students Page Scenario执行到clickOnAddStudentButton()方法的第一行webDriver.findElement(By.id("add-student-btn")).click();时抛出NullPointerException。

核心原因分析

  1. WebDriver实例未跨Scenario维护:第一个Scenario执行时,前置步骤(Open browser and launch application)初始化了WebDriver实例,但测试框架未在第二个Scenario执行前重新初始化,或第一个Scenario执行后销毁了实例,导致第二个Scenario中webDriver变量为null。
  2. 第二个Scenario前置条件缺失:第二个Scenario直接从点击Add student button开始,但该按钮仅存在于Manage Students页面,而此时应用可能处于首页状态——不过此处抛出NPE的直接原因还是webDriver实例为null,而非元素未找到。

解决方案

1. 用Cucumber钩子维护WebDriver生命周期

通过@Before和@After注解在每个Scenario前后初始化、销毁WebDriver,确保每个Scenario都拥有有效实例:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.After;
import io.cucumber.java.Before;

public class Hooks {
    private WebDriver webDriver;

    // 步骤定义类可通过此方法获取WebDriver实例
    public WebDriver getWebDriver() {
        return webDriver;
    }

    @Before
    public void setup() {
        // 根据实际使用的浏览器调整初始化逻辑
        webDriver = new ChromeDriver();
        webDriver.manage().window().maximize();
    }

    @After
    public void teardown() {
        if (webDriver != null) {
            webDriver.quit();
        }
    }
}

步骤定义类中通过钩子类获取WebDriver实例,避免直接使用未初始化的变量。

2. 完善第二个Scenario的前置流程

确保第二个Scenario执行时已进入Manage Students页面,可调整Feature文件:

Feature: Managing Students
Scenario: Manage Students page
Given Open browser and launch application
And Home page is displayed
When User clicks on Manage Students link
Then User sees Manage Students page

Scenario: Create Students Page
Given Open browser and launch application
And Home page is displayed
And User clicks on Manage Students link
And User sees Manage Students page
And Click on Add student button
And New form is displayed
Then Enter details in the form
Then Click submit

也可使用Background提取公共前置步骤,简化Feature文件:

Feature: Managing Students
Background:
Given Open browser and launch application
And Home page is displayed

Scenario: Manage Students page
When User clicks on Manage Students link
Then User sees Manage Students page

Scenario: Create Students Page
And User clicks on Manage Students link
And User sees Manage Students page
And Click on Add student button
And New form is displayed
Then Enter details in the form
Then Click submit

3. 检查WebDriver变量作用域

确保步骤定义类中的webDriver变量是类级别成员,而非局部变量,且能被每个Scenario的步骤方法正确引用。避免在单个方法中创建WebDriver实例后,未传递到其他方法或后续Scenario。

内容的提问来源于stack exchange,提问作者Hamza Mustafa Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:10:31