java - 在 PageFactory 中获取 NPE NullPointerException (Selenium+Java)

标签 java selenium-webdriver pageobjects page-factory

我正在尝试为我的测试框架实现页面工厂模式,但在尝试访问元素或与元素交互时遇到 NPE。顺便说一句,我使用 Spring 依赖注入(inject)在测试之间共享 WebDriver 实例(而不是构造函数),因此我在非静态 block 内实现了 PageFactory initElements() 以便能够访问它。 顺便说一句,如果没有 PageFactory(没有 @FindBy 和带有注释的 By 项目),它就可以完美工作。 这是我的 PO.class 代码:

@Component
public class HomePage extends BasePage {
  @Autowired
  private DatabasesPage databasesPage;
  @Autowired
  private UserAccountsPage userAccountsPage;

  public static Logger log = LogManager.getLogger(HomePage.class.getName());
  private String themeLabelColorHex = "#235a81";
  private Select themeList;

 /* private By databasesHeaderButton = By.cssSelector("#topmenu > li:nth-child(1)"),
             userAccountsHeaderButton = By.cssSelector("#topmenu > li:nth-child(4)"),
             languagesDropdown = By.id("sel-lang"),
             themeDropdown = By.name("set_theme"),
             themeLabel = By.xpath("//*[@id='li_select_theme']//a");*/

  @FindBy(how = How.CSS, css = "#topmenu > li:nth-child(1)")  private WebElement databasesHeaderButton;
  @FindBy(how = How.CSS, css = "#topmenu > li:nth-child(4)")  private WebElement userAccountsHeaderButton;
  @FindBy(how = How.ID, id = "sel-lang") private WebElement languagesDropdown;
  @FindBy(how = How.NAME, name = "set_theme") private WebElement themeDropdown;
  @FindBy(how = How.XPATH, xpath = "//*[@id='li_select_theme']//a") private WebElement themeLabel;

  {
    PageFactory.initElements(driver,this);
    System.out.println("**************** THIS IS A NON-STATIC FIELD REACHED BY DEP INJ ****************");
  }

  public HomePage openUp() {
    String propertiesPath = get(System.getProperty("user.dir"),
      "src", "main", "java", "base", "configuration", "config.properties").normalize().toString();

    try {
      Properties properties = new Properties();
      properties.load(new FileInputStream(propertiesPath));
      String url = properties.getProperty("url");

      driver.get(url);
    }
    catch ( IOException e) {
      log.error("Properties file is not found");
      log.error("\n " + ExceptionUtils.getStackTrace(e));
    }

    return this;
  }

  public DatabasesPage goToDatabasesPage() {
    databasesHeaderButton.click();
    return databasesPage;
  }

  public UserAccountsPage goToUserAccountsPage() {
    userAccountsHeaderButton.click();
    return userAccountsPage;
  }

  public HomePage changeLanguage(String langValue) {
    try {
      Select langList = new Select(languagesDropdown);
      String currentLang = langList.getFirstSelectedOption().getAttribute("value");
      if (langValue.equalsIgnoreCase(currentLang)) log.warn("Desired language is already selected!");
      else langList.selectByValue(langValue);
    }
    catch (Exception e) {
      log.error("\n" + ExceptionUtils.getStackTrace(e));
    }

    return this;
  }

  public HomePage changeTheme(String themeValue) {
    try {
      themeList = new Select(themeDropdown);
      String currentTheme = themeList.getFirstSelectedOption().getAttribute("value");

      if (themeValue.equalsIgnoreCase(currentTheme))
        log.warn("Desired theme is already selected!");
      else {
        themeList.selectByValue(themeValue);
        driver.navigate().refresh();
        themeLabelColorHex = "#0000ff";
      }
    }
    catch (Exception e) {
      log.error("\n" + ExceptionUtils.getStackTrace(e));
    }

    return this;
  }

  public HomePage setDefaultTheme() {
    themeList = new Select(themeDropdown);
    themeList.selectByValue("pmahomme");
    themeLabelColorHex = "#235a81";
    return this;
  }

  public boolean isLanguageChanged() {
    return true; // TO DO
  }

  public boolean isThemeChanged() {
    String RGBColor = themeLabel.getCssValue("color"); // I'm getting NPE here somehow
    String HexColor = Color.fromString(RGBColor).asHex();

    return HexColor.equalsIgnoreCase(themeLabelColorHex);
  }

}

这是我的测试方法:

@Test
  @Description("Change website theme")
  public void changeWebsiteTheme() {
    homePage.openUp().changeTheme("original");
    assertThat(true).isEqualTo(homePage.isThemeChanged()); // and it fails here but it didn't perform previous step - changeTheme();

    homePage.setDefaultTheme();
    assertThat(true).isEqualTo(homePage.isThemeChanged());
  }

enter code here

最佳答案

要启动在构造函数中编写的PageFactory,必须通过创建类的对象来启动它。 this帮助我实现了这一目标。

关于java - 在 PageFactory 中获取 NPE NullPointerException (Selenium+Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61619808/

相关文章:

java - 如何在类中使用字符串作为变量传递字符串作为参数

python - Selenium Python - 获取网络响应主体

JavaFx:Bindings.when().then().otherwise() 处的 NPE

java - 当我想在 Java 的类方法中使用类字段时,定义最终局部变量是一种好习惯吗?

javascript - 如何使用 JavaScript 验证文件是否已成功下载?

javascript - 我需要使用 Protractor 初始化 Spec 文件中的页面对象吗?

protractor - elementfinder promise 是否在声明时得到解决?

java - Spring Data Redis存储库不支持集合查询?

java - 在 JEditorPane 中实现即时文本样式

java - 将 Selenium Java 项目转换为页面对象设计模式时出错