selenium-webdriver - 使用页面工厂初始化 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)
解决方案
当我们做PageFactory设计模式时,我们应该通过页面工厂方法来初始化每个页面。在这里,当您初始化为HomePage homepage = new HomePage();时,您应该得到空点异常;
您应该初始化为 HomePage homePage;
homePage=PageFactory.initElements(Webdriver driver,HomePage.class); 在你的 HomePageTest.java
请删除= new HomePage(); 在你的代码中
推荐阅读
- laravel - laravel如何调用方法
- php - 在 Woocommerce 中,如何找到某个产品交叉销售的所有产品?
- vue.js - 我应该将我所有的 Vue 方法和数据存储在一个文件中吗?
- swift - self.tabBarController?.selectedIndex 并在另一个视图控制器中执行功能
- css - 减少移动设备上按钮和图像之间的间距
- node.js - 使用依赖输出顺序执行 2 个异步函数
- java - 如何更改 ListView 项的文本背景
- android - Android中删除设置时间选项中的TimePicker
- reactjs - 如何动态设置图像或使用默认值
- reactjs - 反应道具消失