0

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 :)

Hoxzy
  • 11
  • 1
    Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Filburt Apr 24 '23 at 07:04
  • Fixed it, i forgot to add public access modifiers for methods in TestBase class, this solved the problem – Hoxzy Apr 24 '23 at 08:15
  • 1
    Since this question is already answered, you should either delete the question or add your own answer and accept it so it doesn't appear to be unanswered. – JeffC Apr 24 '23 at 13:51

1 Answers1

0

Fixed it, i forgot to add public access modifiers for methods in TestBase class, this solved the problem

Hoxzy
  • 11