首页 > 解决方案 > 使用页面工厂初始化 web 元素时出现空指针异常

问题描述

webelements 没有被初始化。

代码如下:

主页.java

package crossword.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import base.TestBase;

public class HomePage extends TestBase{

    @FindBy(xpath = "//title")
    WebElement homepageTitle;

    @FindBy(xpath = "//div[@class=\"top-links\"]//a[text()='Login']")
    WebElement loginLink;

    public HomePage() {
        PageFactory.initElements(driver, this);
    }

    public String gethomepagetitle() {
        return homepageTitle.getAttribute("title");
    }

    public void clickonLogin() {
        loginLink.click();
    }

}

HomePageTest.java

package testcases;

import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import base.TestBase;
import crossword.pages.HomePage;

public class HomePageTest extends TestBase {

    public HomePageTest() {
        super();
    }

    HomePage homepage = new HomePage();

    @BeforeMethod
    public void setUp() {
        TestBase.initialization();
    }

    @Test
    public void homepagetitletest() {
        System.out.print(homepage);
        String actualTitle = homepage.gethomepagetitle();
        String expectedTitle = "Books - Crossword - Crossword";
        Assert.assertEquals(actualTitle, expectedTitle);
    }

    @Test
    public void clickonloginlink() {

        homepage.clickonLogin();

    }

    @AfterMethod
    public void exit() {
        teardown();
    }

}

我得到的错误是:

失败:在 org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java: 38) 在 com.sun.proxy.$Proxy9.click(Unknown Source) at crossword.pages.HomePage.clickonLogin(HomePage.java:25) at testcases.HomePageTest.clickonloginlink(HomePageTest.java:35) at sun.reflect。 Sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.lang.reflect.Method.invoke(Unknown Source) at org.testng。 internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:135) 在 org.testng.internal。TestInvoker.invokeMethod(TestInvoker.java:598) 在 org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)

标签: selenium-webdriverpage-factory

解决方案


当我们做PageFactory设计模式时,我们应该通过页面工厂方法来初始化每个页面。在这里,当您初始化为HomePage homepage = new HomePage();时,您应该得到空点异常;

您应该初始化为 HomePage homePage

homePage=PageFactory.initElements(Webdriver driver,HomePage.class); 在你的 HomePageTest.java

请删除= new HomePage(); 在你的代码中


推荐阅读