我对OOP和Java都很陌生。我在页面对象模式https://www.youtube.com/watch?v=u8XH46u1QAw上看到了这个页面对象工厂的优秀视频。我试图为基本的雅虎网站实现类似的代码,我得到一个Null指针错误。你可以帮我解决这个问题吗?我很感激你的时间。我的代码使用的是testNG
控制台出错:
FAILED: execute
java.lang.NullPointerException
at PageObject.SearchPage.updateSearch(SearchPage.java:16)
代码:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import PageObject.SearchPage;
public class PgMain {
WebDriver Browser;
@BeforeTest
public void start(){
Browser=new InternetExplorerDriver ();
}
@Test
public void execute(){
SearchPage s=new SearchPage(Browser);
s.navigateTo();
s.updateSearch();//This is when I get the NPE
}
@AfterTest
public void stop(){
}
}
package PageObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public abstract class Abs {
WebDriver Browser;
public Abs(WebDriver Browser){
this.Browser=Browser;
}
public SearchPage navigateTo(){
Browser.get("http://finance.yahoo.com/");
return PageFactory.initElements(Browser, SearchPage.class);
}
}
package PageObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class SearchPage extends Abs {
@FindBy (id="UHSearchProperty")
private WebElement searchFinancebtn;
@FindBy (id="UHSearchBox")
private WebElement usersearchBox;
public SearchPage(WebDriver Browser){
super(Browser);
}
public SearchPage updateSearch(){
usersearchBox.sendKeys("GOOG");//NPE
searchFinancebtn.click();
return PageFactory.initElements(Browser, SearchPage.class);
}
}
答案 0 :(得分:0)
initElements
只在navigateTo()
调用期间返回的SearchPage实例上SearchPage s = new SearchPage(Browser);
s.navigateTo().updateSearch();
。
因此,要使您的代码正常工作,您必须执行以下操作:
WebDriver driver;
SearchPage searchPage;
@Before
public void start() {
driver = new InternetExplorerDriver();
searchPage = PageFactory.initElements(driver, SearchPage.class);
}
@Test
public void execute() {
s.navigateTo();
s.updateSearch();
}
但说实话,这看起来很难看。为什么不只是做以下事情:
{{1}}
此外,我也质疑该视频的优秀性。