[英]“NullPointerException” on trying to run my script using PageFactory
我已經附上了POM,BaseTest和Test類。 我試圖通過右鍵單擊項目以將其作為TestNG測試運行,從而獲得以下代碼的NullPointerException。 請可以建議嗎?
POM類別:
package pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Introduction
{
@FindBy(xpath="//a[text()='Hello. Sign In']")
WebElement signInLink;
public Introduction(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
public void signIn()
{
signInLink.click();
}
}
BaseTest類:
package scripts;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;
public class BaseTest
{
public WebDriver driver;
@BeforeSuite
public void preCondition()
{
driver= new FirefoxDriver();
driver.get("https://www.walmart.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterSuite
public void postCondition()
{
driver.close();
}
}
測試類別:
package scripts;
import org.testng.annotations.Test;
import pom.Introduction;
public class SignIn extends BaseTest
{
@Test
public void validSignIn()
{
Introduction i= new Introduction(driver);
i.signIn();
}
}
您的代碼有幾個問題。
@BeforeSuite
中實例化@BeforeSuite
。 這將導致每個<suite>
標簽僅創建一次您的webdriver實例。 因此,所有其他@Test
方法將始終獲得NullPointerException
因為@BeforeSuite
注釋的方法不會第二次執行。 因此,一開始,我建議您將測試代碼更改為如下所示
BaseTest.java
package scripts;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;
public class BaseTest {
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
@BeforeMethod
public void preCondition() {
driver.set(new FirefoxDriver());
driver.get().get("https://www.walmart.com/");
}
@AfterMethod
public void postCondition() {
driver.get().quit();
}
public final WebDriver driver() {
return driver.get();
}
}
SignIn.java
package scripts;
import org.testng.annotations.Test;
import pom.Introduction;
public class SignIn extends BaseTest {
@Test
public void validSignIn() {
Introduction i = new Introduction(driver());
i.signIn();
}
}
在這里,我們選擇使用@BeforeMethod
和@AfterMethod
進行@AfterMethod
的實例化和清理,因為可以保證這些方法在每個@Test
方法之前和之后執行。 然后,我們繼續使用Webdriver
ThreadLocal
變體,因為ThreadLocal確保每個線程都擁有自己的webdriver副本,以便您可以輕松地開始並行運行測試。 現在這不是問題,但是很快您將在開始構建實現時遇到這個問題。 通過閱讀我的這篇博客文章,您可以了解有關如何使用TestNG進行並行執行的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.