Issue
Im working whit Selenium and Java.
And i was doing a test to a web demo and was working fine, but now is displaying an nullpointerexception error, i though was something about using the @FindBy but using the WebElement is also failing, i think is something of the class where i do the methods, i try with other question here but nothing works
This is my constructor
public class PageObject {
protected WebDriver driver;
public PageObject(WebDriver driver){
this.driver = driver;
PageFactory.initElements(this.driver, this);
}
This is where search the elements
public class Home_Page extends PageObject {
public Home_Page(WebDriver driver) {
super(driver);
}
@FindBy(id = "nava")
public static WebElement logo;
}
The page where i do the steps
public class Home_Page_Steps {
public WebDriver driver;
public void clickLogo(){
Home_Page.logo.click();
//driver.findElement(By.id("nava"));
}
}
And the page where i call the methods
public class home_Page {
public WebDriver driver = new ChromeDriver();
Home_Page_Steps hps = new Home_Page_Steps();
@BeforeSuite
public static void main(String[] args){
//driver.manage().deleteAllCookies();
System.setProperty("wedriver.chrome.driver", Utils.PathDriver);
}
@Test()
public void openWebPage(){
driver.get(Utils.BASE_URL);
//driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
}
@Test(testName = "Click Logo")
public void clickLogo(){
openWebPage();
hps.clickLogo();
//WebElement logo = driver.findElement(By.id("nava"));
//logo.click();
//hps.clickLogo();
}
}
Solution
You are getting NullPointerException
, because you marked it as static
field.
Static instances are initialized in Runtime before constructor or non-static fields. And they don't need class object to be created.
You declared driver
as an class field, so when you get class static property, this field is null
(static instance initialization block doesn't know anything about non-static fields).
To initialize driver you need to pass it inside class contstructor in steps class and create new instance of Home_Page
inside.
public class Home_Page_Steps {
private WebDriver driver;
public Home_Page_Steps(WebDriver driver) {
this.driver = driver;
}
public void clickLogo(){
new Home_Page(driver).logo.click();
}
}
Answered By - Yaroslavm
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.