javaseleniumselenium-webdriverfindby

Getting error when using FindBy in selenium. Error message null point exception


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();

    }
}

Getting error on line "HotelLink.click" and that hotelLink element is defined using findBy annotation but getting "java.lang.NullPointerException" error


Solution

  • Since you are using @FindBy annotation you have to initialize the element before using.

    you can do that by creating parameterized constructor accepting WebDriver type as argument.

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