I am encountering a java.lang.NullPointerException error when trying to run my Selenium test with TestNG. The error message states: Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null.
I have provided the relevant code snippets below:
LandingPage (Page Object class):
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LandingPage {
@FindBy(linkText = "Enter the Store")
private WebElement linkToStore;
public LandingPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void enterTheStore() {
linkToStore.click();
}
}
TestBase (Test base class):
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import java.time.Duration;
public class TestBase {
public WebDriver driver;
@BeforeTest
void setUpAll() {
WebDriverManager.chromedriver().setup();
}
@BeforeMethod
void setupEach() {
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("http://przyklady.javastart.pl/jpetstore/");
}
@AfterMethod
void quit() {
driver.close();
driver.quit();
}
}
FailedLoginTest (Test class):
import com.javastart.buildingFramework.page.objects.LandingPage;
import com.javastart.tests.base.TestBase;
import org.testng.annotations.Test;
public class FailedLoginTest extends TestBase {
@Test
void failedLoginTest() throws InterruptedException {
LandingPage landingPage = new LandingPage(driver);
landingPage.enterTheStore();
}
}
When I try to run FailedLoginTest, I got this error: java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null and Im not sure why is it being thrown. Any help will be appreciated :)