使用 Selenium Wedriver Practical Guide 中的示例(登录并在 Wordpress 上创建测试帖子),我遇到了上述错误。
这是我正在使用的 PageObject:
package com.PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
/**
* Created by JTester on 3/9/2016.
*/
public class AdminLoginPage {
WebDriver driver;
@FindBy(how=How.ID, id="user_login")
WebElement email;
@FindBy(how=How.ID, id="user_pass")
WebElement pwd;
@FindBy(how=How.ID, id="wp-submit")
WebElement submit;
public AdminLoginPage(WebDriver driver){
this.driver = driver;
driver.get("http://mysite.wordpress.com/wp-admin/");
}
public void login(){
email.sendKeys("myEmailAddress@yahoo.com");
pwd.sendKeys("myPasswd");
submit.click();
}
}
这是测试类:
package com.features.trial;
import com.PageObjects.AdminLoginPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
* Created by JTester on 3/9/2016.
*/
public class TestAddNewPost {
public static void main(String... args) {
WebDriver driver = new FirefoxDriver();
//login to wordpress admin
AdminLoginPage admLoginPage = new AdminLoginPage(driver);
admLoginPage.login();
//go to AllPosts page
driver.get("http://mysite.wordpress.com/wp-admin/edit.php");
//add a new post
WebElement addNewPost = driver.findElement(By.linkText("Add New"));
addNewPost.click();
//add new post's content
driver.switchTo().frame("content_ifr");
WebElement postBody = driver.findElement(By.id("tinymce"));
postBody.sendKeys("This is my description.");
driver.switchTo().defaultContent();
WebElement title = driver.findElement(By.id("title"));
title.sendKeys("This is my first post");
//publish my post
WebElement publish = driver.findElement(By.id("publish"));
publish.click();
}
}
由于我是 Selenium 和 Page Objects 的新手,任何人都可以解释为什么它会引发以下错误:
Exception in thread "main" java.lang.NullPointerException
at com.PageObjects.AdminLoginPage.login(AdminLoginPage.java:29)
at com.features.trial.TestAddNewPost.main(TestAddNewPost.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Process finished with exit code 1
非常感谢..
ps:在网上看了很多代码示例后,我想我需要使用 PageFactory 来实例化我的元素,但不确定这是否正确,如果是,我该如何使用我的示例代码进行操作。