我試圖找到答案,但沒有人幫助我。我確定我錯過了一個細節,但我無法弄清楚究竟是什麼。運行測試用例時得到NullPointerException
。當我嘗試將驅動程序傳遞給從WebPage
(超類)繼承的頁面對象(WikiMain
)時,我認爲會發生這種情況,因爲當我調試時,我注意到了driver = null。我應該將驅動程序傳遞給WebPage
,因爲其他頁面是從它繼承的? P.S.對不起,我對這件事很陌生,這是我在這個網站上的第一個問題。使用PageObjects模式運行測試時出現NullPointerException
這裏是我的測試用例類:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
public class TestCase{
public WebDriver driver;
@BeforeTest
public void setUp(){
driver = new ChromeDriver();
}
@AfterTest
public void tearDown(){
driver.quit();
}
public WebPage getWikiMain(){
driver.get("https://www.wikipedia.org/");
return new WikiMain(driver);
}
}
這裏是我的網頁類:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class WebPage{
private WebDriver driver;
public WebPage(WebDriver driver){
this.driver = driver;
initWebElements();
}
public void initWebElements(){
PageFactory.initElements(driver, this);
}
}
這裏是WikiMain類:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class WikiMain extends WebPage{
private WebDriver driver;
public WikiMain(WebDriver driver){
super(driver);
}
public WebPage getWikiEn(){
String linkToWikiEn = driver.findElement(By.xpath(".//*[@class= 'central-featured-lang lang1']/a")).getAttribute("href");
driver.get(linkToWikiEn);
return new WikiMainEn(driver);
}
}
而且WikiMainEn類:
package com.company.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class WikiMainEn extends WebPage{
private WebDriver driver;
public WikiMainEn(WebDriver driver){
super(driver);
}
@FindBy(xpath = ".//*[@id='mp-topbanner']/tbody/tr/td[1]/table/tbody/tr/td/div[1]")
private WebElement title;
public WebElement getTitle(){
return title;
}
public String getTitleText(){
return getTitle().getText();
}
}
而實際測試:
import com.company.pages.*;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestWikiMain extends TestCase{
@Test
public void verifyEnWiki() {
WikiMain wikiMain = (WikiMain) getWikiMain();
WikiMainEn wikiMainEn = (WikiMainEn) wikiMain.getWikiEn();
Assert.assertTrue(wikiMainEn.getTitleText().contains("Welcome to"));
}
在你的'測試用例()'類,應該註釋是@的'BeforeClass'代替'@ BeforeTest'(按照[TestNG的主頁示例](HTTP: //testng.org/doc/index.html)SimpleTest.java)? – Bobulous
@Bobulous, 是的,它可以是BeforeClass或BeforeMethod,我只是使用BeforeTest,因爲我正在使用DataProvider進行練習,而我並沒有取代它。但這並沒有什麼不同。 –