[英]I get NullPointerException when trying to click button that exists and initialized with PageFactory.initElements()
Say, I have two little tests within one class. 说,我在一堂课里做了两个小测试。
public class LoginAndLogout extends BaseTest {
HomePage kashome = new HomePage();
@Test(testName = "Login_as")
public void login() {
LoginPage loginkas = LoginPage.open(); //open login page
kashome = loginkas.login(name, pwd);
}
@Test
public void logOut() {
kashome.logOut();
}
}
HomePage class: 主页类:
public class HomePage extends BasePage {
public HomePage() {
PageFactory.initElements(Driver.get(), this);
}
}
BasePage class: BasePage类:
public class BasePage {
@FindBy(xpath="//img[@title='Выход']")
WebElement exitButton;
@FindBy (xpath="//a[text()='Выход']")
WebElement exitLink;
public BasePage() {
PageFactory.initElements(Driver.get(), this);
}
public boolean isLoggedIn(String usr) {
if (this.usernameText.getText().startsWith(usr)) return true;
else return false;
}
public void logOut() {
try {
exitLink.click();
Alert alert = Driver.get().switchTo().alert();
Reporter.log(alert.getText(), true);
Reporter.log("Отвечаем ОК", true);
alert.accept();
}
catch (UnhandledAlertException e) {
e.printStackTrace();
Reporter.log(e.getMessage(), true);
}
catch (Exception e) {
e.printStackTrace();
Reporter.log(e.getMessage(), true);
}
}
}
1st test runs OK, but on second test I get NPE when trying to execute exitLink.click(), seems like elements in kashome is not initialized, but they are! 第一个测试运行正常,但是在第二个测试中,当我尝试执行exitLink.click()时,我得到了NPE,好像kashome中的元素未初始化,但是它们是初始化的! There is no @AfterTest methods that could affect tests' behavior. 没有@AfterTest方法可能会影响测试的行为。 I checked button's xpath, it's ok. 我检查了按钮的xpath,没关系。 However, if I add kashome.logOut() to 1st test and delete 2nd one, everything works ok. 但是,如果我将kashome.logOut()添加到第一个测试并删除第二个测试,则一切正常。
Why do I get NPE? 为什么我要获得NPE?
If the PageFactory
doesn't process the annotations on exitLink
and exitButtons
, because those aren't initialized explicitly, they will default to null
when your HomePage
instance is created. 如果PageFactory
不处理exitLink
和exitButtons
上的注释,因为它们未显式初始化,则在创建HomePage
实例时它们将默认为null
。
I think you are assuming that 我想你是在假设
@FindBy(xpath="//img[@title='Выход']")
WebElement exitButton;
@FindBy (xpath="//a[text()='Выход']")
WebElement exitLink;
because of the @FindBy
annotations, will have values when you run your tests. 由于@FindBy
批注,因此在运行测试时将具有值。 Annotations on their own don't do anything. 注释本身没有任何作用。 You need some processor to read them and, through reflection, set the field they are annotating. 您需要一些处理器来读取它们,并通过反射来设置它们正在注释的字段。 If PageFactory
doesn't do that, those fields will remain null until you set them yourself. 如果PageFactory
不这样做,那么在您PageFactory
设置之前,这些字段将保持为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.