为什么我的驱动程序在构造函数调用时没有调用?

why my driver is not invoking when called by a constructor?

提问人:Sana Sameer 提问时间:4/19/2023 最后编辑:JeffCSana Sameer 更新时间:4/19/2023 访问量:37

问:

我创建了一个 POM 结构,其中在主类中初始化并使用构造函数在页面类中调用。问题是 url 也是从一个名为 s1 登录页面的页面类之一传递的,但它没有调用,只有 chrome 被打开。URL 未传递。driver

主类

public class Sample1 {
    public static void main(String[] args) {
        String item = "ADIDAS ORIGINAL";
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

        S1LandingPage S1landingPage = new S1LandingPage(driver);
        S1landingPage.Goto();
        S1landingPage.login("[email protected]","Sana@1234");
    }
}

S1登陆页面

public class S1LandingPage extends Sample1 {
    WebDriver driver;

    public S1LandingPage(WebDriver driver) {
        driver = this.driver;
        PageFactory.initElements(driver, this); //to get driver for local variables made by find by 
    }

    @FindBy(id="userEmail")
    WebElement Uname;

    @FindBy(id="userPassword")
    WebElement pw;

    @FindBy(id="login")
    WebElement submit;

    public void login(String email, String passwrd) {
        Uname.sendKeys(email);
        pw.sendKeys(passwrd);
        submit.click();
    }

    public void Goto()  {
        driver.get("https://rahulshettyacademy.com/client/"); 
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    }
}

错误

Exception in thread "main" java.lang.NullPointerException
    at pageObjects.S1LandingPage.Goto(S1LandingPage.java:45)
    at rahulshety.EndtoEnd.Sample1.main(Sample1.java:33)
selenium-webdriver 自动化 pom.xml webdriver-manager chrome-options

评论


答:

0赞 JeffC 4/19/2023 #1

构造函数中的赋值是向后的。

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

应该是

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

this引用当前对象 。所以,是类的属性,是参数。S1LandingPagethis.driverdriverS1LandingPagedriverdriver

请参阅有关使用情况的文档this