比方说,我在一个类中有两个小测试。
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();
}
}
主页类别:
public class HomePage extends BasePage {
public HomePage() {
PageFactory.initElements(Driver.get(), this);
}
}
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);
}
}
}
第一次测试运行正常,但在第二次测试中,当我尝试执行exitLink.click()时,我得到了NPE,看起来kashome中的元素没有初始化,但它们确实初始化了!没有可能影响测试行为的@AfterTest方法。我检查了按钮的xpath,没问题。然而,如果我在第一次测试中添加kashome.logOut()并删除第二次测试,一切都会正常
为什么我会得到NPE?
如果PageFactory
不处理exitLink
和exitButtons
上的注释,因为它们没有显式初始化,那么在创建HomePage
实例时,它们将默认为null
。
我想你是在假设
@FindBy(xpath="//img[@title='Выход']")
WebElement exitButton;
@FindBy (xpath="//a[text()='Выход']")
WebElement exitLink;
由于@FindBy
注释,在运行测试时将具有值。注释本身没有任何作用。您需要一些处理器来读取它们,并通过反射来设置它们正在注释的字段。如果PageFactory
不这样做,那么这些字段将保持为空,直到您自己设置它们为止。