我希望用WebDriver
在selenium PageFactory
中编写测试,但如果我在课程中以PageFactory
形式添加注释
@FindBy(id="email")
public WebElement mailLink;
和用法:
mailLink.sendKeys("mail@mail.com");
我每次都得NullPointerException
。另一种方式:
driver.findElement(By.id("email")).sendKeys("mail@mail.com");
返回正确的值。第一种方法的问题在哪里?
我的代码:
我在FaceClass中进行了驱动程序初始化:
public class FaceClass {
protected WebDriver driver;
public FaceClass(WebDriver driver){
this.driver = driver;
}
public HomePage navigateToApp(){
driver.navigate().to("https://facebook.pl");
return PageFactory.initElements(driver, HomePage.class);
}
}
和具有业务逻辑的类:
public class HomePage extends FaceClass{
public HomePage(WebDriver driver) {
super(driver);
// TODO Auto-generated constructor stub
}
@FindBy(id="email")
public WebElement mailLink;
@FindBy(id="pass")
public WebElement passLink;
@FindBy(how = How.ID, using="u_0_n")
public WebElement loginButton;
public ProfilePage navigateToProfile(){
try{
if(driver.findElement(By.id("pass")).isEnabled() || driver.findElement(By.id("pass")).isDisplayed()){
System.out.println("ok!");
}
//driver.findElement(By.id("pass")).sendKeys("pass_to_account");
//driver.findElement(By.id("email")).sendKeys("mail@mail.com");
//driver.findElement(By.id("u_0_n")).click();
mailLink.sendKeys("mail@mail.com");
passLink.sendKeys("pass_to_account");
loginButton.click();
} catch (Exception e) {
e.printStackTrace();
}
return PageFactory.initElements(driver, ProfilePage.class);
}
}
并测试:
public class ExampleTest {
WebDriver driver;
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setCapability("marionette", true);
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to("https://facebook.pl");
}
@After
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void test() {
//fail("Not yet implemented");
HomePage homepage = new HomePage(driver);
homepage.navigateToProfile();
}
}
所有元素均已启用且可见
答案 0 :(得分:1)
在使用之前,您没有初始化元素。初始化页面元素PageFactory方法initElements。如果你在你的构造函数中调用它会更好:
public HomePage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
希望它有效。