'Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null
The below code is failing in homeSignInLink.click(); and giving error
"NullPointerException: Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null
Code
public class LoginTest extends TestBase
{
WebDriver driver;
HomePage objHomePage = new HomePage(driver);
@Test
public void login_check()
{
objHomePage.clickHomeSignInLink();
objHomePage.clickRecruiterSignInLink();
}
}
public class HomePage
{
WebDriver driver;
@FindBy(xpath="//a[@class='nav-link bold' and text()='Sign in']") WebElement homeSignInLink;
@FindBy(xpath="//a[text()='Recruiter sign in']") WebElement recruiterSignInLink;
public HomePage(WebDriver driver)
{
this.driver = driver;
//This initElements method will create all WebElements
PageFactory.initElements(driver, this);
}
public void clickHomeSignInLink()
{
homeSignInLink.click();
}
public void clickRecruiterSignInLink()
{
recruiterSignInLink.click();
}
}
Solution 1:[1]
Please use the same WebDriver instance from your TestBase class throughout all the scripts. Ex., in LoginTest class remove the WebDriver declaration and modify the line:
HomePage objHomePage = new HomePage(TestBase.driver);
Make the WebDriver instance as static in TestBase class.
Solution 2:[2]
WebDriver driver; You are freshly declaring hence its null.
public class LoginTest extends TestBase { //Comment this as you are already extending TestBase // WebDriver driver;
//Also instead of mentioning driver //= new Chromedriver(); // in before //method..write it here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AbiSaran |
| Solution 2 |
