簡體   English   中英

嘗試使用PageFactory運行我的腳本時出現“ NullPointerException”

[英]“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注釋的方法不會第二次執行。
  • 您正在使用隱式超時。 請不要使用隱式超時。 您可以在這篇 SO文章中了解有關隱式等待的弊端的更多信息。

因此,一開始,我建議您將測試代碼更改為如下所示

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM