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”错误
由于您使用的是@FindBy注释,因此必须在使用前初始化该元素。
你可以通过创建接受WebDriver类型作为参数的参数化构造函数来做到这一点。
PageFactory.initElements(driver, this);```
and call this constructor after opening the browser.
i.e after this line
```driver = new ChromeDriver();```
在使用@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
。
我希望它有所帮助......
对于qazxsw poi注释,您需要在搜索WebElement之前实现它。
您可以通过简单的方式添加为您执行此操作的方法:
@FindBy