java - 如何初始化驱动程序以避免 NullPointerException 错误

标签 java eclipse selenium testng

我在使用此类时遇到问题,收到空指针异常。我插入System.out.println("driver=" + driver);查看输出内容,它指出 driver=null对于每个数据集,当我点击@Test下的方法时,这让我认为初始化存在问题。如何解决驱动程序的初始化以使我的测试在 testNG 中通过?

下面是代码:

package com.testng.practice;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

    public class LoginTest {

        WebDriver driver = null;

        @BeforeTest
        public void invokeApplication() {
            System.setProperty("webdriver.chrome.driver", "xxx\\chromedriver.exe");
            WebDriver driver = new ChromeDriver(); 
            driver.manage().window().maximize();
            driver.get("https://www.facebook.com");
        }   

        @Test (dataProvider = "getData")
        public void loginFaceBook(String email, String password) {

            System.out.println("driver=" + driver); 

            WebElement emailField = driver.findElement(By.name("email"));
            WebElement passwordField = driver.findElement(By.name("pass"));

            emailField.sendKeys(email);
            passwordField.sendKeys(password);

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @DataProvider
        public Object[][] getData(){

            //declared object of 4 rows and 2 columns

            Object[][] dataSet = new Object[4][2];

            dataSet[0][0] = "TimSmith@gmail.com";
            dataSet[0][1] = "Smith123";

            dataSet[1][0] = "JaneMcCormack@gmail.com";
            dataSet[1][1] = "McCormack123";

            dataSet[2][0] = "AnjaliPrakash@gmail.com";
            dataSet[2][1] = "Prakash123";

            dataSet[3][0] = "JamesBean@gmail.com";
            dataSet[3][1] = "Bean123";

            return dataSet;

        }
    }

最佳答案

driver 变量的定义在 invokeApplication() 方法中有效,并且使类属性 driver 未初始化

WebDriver 驱动程序 = new ChromeDriver();

初始化类属性使用:

this.driver = new ChromeDriver();

关于java - 如何初始化驱动程序以避免 NullPointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125111/

相关文章:

java - 如何将事件的开始时间和结束时间与其他事件的开始时间和结束时间进行比较

java - 在 Android 中从导入的 jar 中读取资源

java - 如何更改 Javadoc 的包以查找源文件?

eclipse - 如何将selenium javadoc绑定(bind)到eclipse

java - 使用 Spring 代理时如何查看和调试 Web 服务响应?

java - Springboot 没有 [javax.sql.DataSource] 类型的限定 bean

java - apache httpcomponent 和 sftp 协议(protocol) - 可以使用该协议(protocol)吗?

eclipse - plugin.xml 中的可选扩展点

java - Selenium WebDriver 中 org.openqa.selenium.remote.session.StripAnyPlatform 类的用途是什么?

javascript - Chrome onMessage监听器总是发送 'undefined'响应