Java /硒-java.lang.NullPointerException

时间:2018-07-05 07:03:34

标签: java selenium junit

执行测试时,我有这个“ java.lang.NullPointerException”。 如何解决此问题?已经检查了其他主题,但是仍然有一些麻烦。 将很高兴解决这个问题。

测试(单击登录页面):

public class MainPage {
private WebDriver driver;

static WebDriver wait;

public MainPage(WebDriver driver) {
this.driver = driver;
}

@FindBy (xpath = "//a[text()='Sign in']" )
private WebElement signInButton;

public LoginPage clickSignIn() {
    signInButton.click();
    return new LoginPage(driver);
}

主要:

public class MainPageTest {
private WebDriver driver;
private MainPage mainPage;


@Before
public void setUp() {
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("https://github.com");
    mainPage = new MainPage(driver);

}

@Test
public void signInTest(){
    LoginPage loginPage = mainPage.clickSignIn();
    String heading = loginPage.getHeadingText();
    Assert.assertEquals("Sign in to GitHub", heading);
}

@After
public void tearDown(){
    driver.quit();
}

LoginPage类:

public class LoginPage {
WebDriver driver;

public LoginPage(WebDriver driver){
    this.driver = driver;
}

private By loginField = By.xpath(".//*[@id='login_field']");
private By passwordField = By.xpath(".//*[@id='password']");
private By signInButton = By.xpath("//input[@type='submit']");
private By heading = By.xpath("//div[contains(@class, 'auth-form-   header')]/h1");
private By error = By.xpath(".//*[@id='js-flash-container']//div[@class='container']");
private By createAccLink = By.xpath("//a[text()='Create an account']");

2 个答案:

答案 0 :(得分:0)

您尚未初始化页面对象Model类,因此引发了NULL指针异常。因此,signInButton需要按如下所示在clickSignIn按钮内移动

public LoginPage clickSignIn() {
    WebElement signInButton=driver.findElement(By.xpath("//a[text()='Sign in']"));
    signInButton.click();
    return new LoginPage(driver);
}

其他

您需要按如下所示初始化MainPage类

    public MainPage(WebDriver driver) {
        this.driver = driver;
        PageFactory.initElements(driver, this);
    }

答案 1 :(得分:0)

空指针异常即将到来,因为您尚未初始化Pagefatory类。

有关脚本编写的信息,请参见下面的博客

http://toolsqa.com/selenium-webdriver/page-object-pattern-model-page-factory/