在selenium中使用FindBy时出错。错误消息空点异常

问题描述 投票:1回答:3
import com.sun.javafx.PlatformUtil;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class HotelBookingTest {
    WebDriver driver;
    @FindBy(xpath= "//*[@class='hotelApp ']")
    public static WebElement hotelLink;


    @Test
    public void shouldBeAbleToSearchForHotels() {
        setDriverPath();
        driver = new ChromeDriver();
        driver.get("https://www.cleartrip.com/");
        boolean hotelLinkDisplayed = hotelLink.isDisplayed();

       hotelLink.click();
        driver.quit();

    }
}

在“HotelLink.click”行上获取错误,并使用findBy注释定义了hotelLink元素,但收到“java.lang.NullPointerException”错误

java selenium selenium-webdriver findby
3个回答
1
投票

由于您使用的是@FindBy注释,因此必须在使用前初始化该元素。

你可以通过创建接受WebDriver类型作为参数的参数化构造函数来做到这一点。

        PageFactory.initElements(driver, this);```

and call this constructor after opening the browser.
i.e after this line 
```driver = new ChromeDriver();```

3
投票

在使用@FindBy注释时,需要在使用之前初始化所有Web元素。

HotelBookingTest类创建一个构造,并使用PageFactory进行初始化,如下所示:

import com.sun.javafx.PlatformUtil;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class HotelBookingTest {
    WebDriver driver;

    @FindBy(xpath= "//*[@class='hotelApp ']")
    public WebElement hotelLink;

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

    @Test
    public void shouldBeAbleToSearchForHotels() {
        setDriverPath();
        driver = new ChromeDriver();
        new HotelBookingTest(driver);
        driver.get("https://www.cleartrip.com/");
        boolean hotelLinkDisplayed = hotelLink.isDisplayed();

        hotelLink.click();
        driver.quit();
    }
}

从相应的包中导入PageFactory并在`hotelLink之前删除static

我希望它有所帮助......


2
投票

对于qazxsw poi注释,您需要在搜索WebElement之前实现它。

您可以通过简单的方式添加为您执行此操作的方法:

@FindBy
© www.soinside.com 2019 - 2024. All rights reserved.