繁体   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