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

Selenium POM中CampaignPage对象空指针异常(NPE)求助

Selenium POM框架中NullPointerException问题的解决方法

问题根源

TestNG的@BeforeTest注解作用域为<test>标签级别,在同一个<test>下仅执行一次,且仅在第一个测试类(LoginPageTest)的实例上执行initPageObjects方法初始化页面对象。而CampaignPageTest作为独立的BaseTest子类实例,其campaignPage变量未被初始化,始终为null,调用方法时触发NullPointerException。

解决方案

将BaseTest中的@BeforeTest注解替换为@BeforeClass,该注解会在每个测试类的第一个测试方法执行前执行,确保每个测试类实例都能初始化自己的页面对象。

修改后的BaseTest代码

package com.paytm;

import com.paytm.base.BaseSetup;
import com.paytm.pages.CampaignPage;
import com.paytm.pages.LoginPage;
import org.testng.annotations.*;

public class BaseTest extends BaseSetup {

    LoginPage loginPage;
    CampaignPage campaignPage;

    @BeforeClass // 替换@BeforeTest为@BeforeClass
    public void initPageObjects(){
        loginPage = new LoginPage(driver);
        campaignPage = new CampaignPage(driver);
    }

    @BeforeSuite
    public void setupBrowser(){
        driver = initDriver();
    }

    @AfterSuite
    public void tearBrowser(){
        driver.quit();
    }
}

额外优化建议(提升稳定性)

  1. 修正LoginPage中的XPath语法错误:

    • @FindBy(xpath = "a[contains(text(),'Accept')]") → @FindBy(xpath = "//a[contains(text(),'Accept')]")
    • @FindBy(xpath = "//iframe[@id=']iframe']") → @FindBy(xpath = "//iframe[@id='iframe']")
    • @FindBy(xpath = "//input[@]id='input_email']") → @FindBy(xpath = "//input[@id='input_email']")
    • @FindBy(xpath = "//input[@oid='input_password']") → @FindBy(xpath = "//input[@id='input_password']")
  2. BaseSetup中添加浏览器配置校验:

    public WebDriver initDriver(){
        if ("chrome".equalsIgnoreCase(browser) && browser != null){
            driver = new ChromeDriver();
            driver.get(config.getProperty("url"));
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
        } else {
            throw new IllegalArgumentException("Browser not configured or unsupported: " + browser);
        }
        return driver;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:55:54