Avoiding Selenium POM and TestNG NullPointerExceptions

I am currently working on automating my tests using web driver, testng, and the page factory. However, I have encountered a null pointer exception while executing the code provided below.

HomePage Page Object Class

This is the page factory class.

package POM;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class HomePage 
{       
    WebDriver driver;
    private static WebElement element = null;

    public HomePage(WebDriver driver)
    {
        this.driver = driver;
    }

    public static WebElement signin(WebDriver driver)
    {
        element=driver.findElement(By.xpath("/html/body/div/div[1]/header/div[2]/div/div/nav/div[1]/a"));
        return element;
    }

    public static WebElement emailCreate(WebDriver driver)
    {
        element=driver.findElement(By.id("email_create"));
        return element;
    }

    public static WebElement submitCreate(WebDriver driver)
    {
        driver.findElement(By.id("SubmitCreate"));
        return element;
    }

}

This is the Test Class for executing actual tests. Test Case Class

package POM;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;

import POM.HomePage;

public class MyTest {


    private static WebDriver driver = null;

  @BeforeMethod
  public void beforeMethod() 
  {

        System.setProperty("webdriver.chrome.driver", "C:/chromedriver_win32/chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.get("http://www.automationpractice.com");
        System.out.println("Hi");
        driver.manage().window().maximize();  
  }

  @Test
  public void login() throws InterruptedException 
  {
      System.out.println("login");
      HomePage.signin(driver).click();
      String title = driver.getTitle();
      System.out.println(title);
      HomePage.emailCreate(driver).sendKeys("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfbaa3a4aea78fb7bfaea1b7a6a0a1e1aca0e1a6a1">[email protected]</a>");
      Thread.sleep(2000);
      HomePage.submitCreate(driver).click();

  }

  @AfterMethod
  public void afterMethod() 
  {
      driver.close();
  }

}

Exception Encountered:

[RemoteTestNG] detected TestNG version 6.14.2
Starting ChromeDriver 2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91) on port 42928
Only local connections are allowed.
Apr 19, 2018 2:48:27 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Hi
login
FAILED CONFIGURATION: @AfterMethod afterMethod
java.lang.NullPointerException
...
... (error message shortened for brevity)
...

===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
Configuration Failures: 1, Skips: 0
===============================================

If anyone could provide assistance in resolving this error, it would be greatly appreciated.

Answer №1

There seems to be an issue with the driver being null, which is why you are encountering those exceptions.

Consider updating

private static WebDriver driver = null;

To

private static WebDriver driver = new FirefoxDriver();

Or in your beforeMethod section, update by replacing

WebDriver driver=new ChromeDriver();

With

driver=new ChromeDriver();

This will prevent the creation of a second driver variable.

Answer №2

To avoid encountering a null pointer exception in your code, it is important not to create the "driver" object more than once.

It seems that in your test case you have instantiated the driver object twice:

1st - Declared as a Class variable: private static WebDriver driver = null;

2nd - Instantiated in the @Before method: WebDriver driver=new ChromeDriver();

To resolve this issue, remove the "WebDriver" keyword from the second instance and instead use: "driver = new ChromeDriver();"

By following this modification, you will eliminate the null pointer exception and allow your code to run smoothly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What purposes does the pom.xml file serve in Maven other than managing dependencies for Selenium?

I'm looking for some clarification on the interview question related to the pom.xml file: Aside from managing dependencies in Selenium, what other purposes does the pom.xml file serve? ...

When attempting to generate a chrome instance using a different profile, new instances are created by chrome that are not linked to selenium

I am facing issues connecting to Chrome with the selected profile via options. Below is the code snippet: options.add_argument('--user-data-dir={}'.format(user_data_dir)) options.add_argument('--profile-dir={}'.format(profile_dir)) Eve ...

Develop an array of JSON Objects within a Java environment

My task involves handling a CSV file with 10 columns and multiple rows. The goal is to convert each row into a JSON object. An example of the file structure is as follows: Name, Age, Address..........and other columns ABCD, 23 , HOME.............and other ...

Discovering elements in a web page with Selenium

I need help identifying elements in a list: <ul> <li></li> <li></li> <li style="display: none"></li> <li style="display: none"></li> <li style="display: none"></li> ...

Prevent the "Disable Developer Mode Extensions" Popup from Appearing When Installing an Extension in Selenium

I am looking to prevent the "Disable Developer Mode Extensions" popup from appearing, while still using an extension mentioned in this thread keep "Disable developer mode" closed while adding extension Since no solution was provided, I am also a ...

The method Element.getText() will return an empty string

This image displays a field that is pre-populated from the API, and I am attempting to automate it using the command below. Once it's available, I check if it's not null. https://i.stack.imgur.com/xSAte.png <div class="MuiInputBase-root Mu ...

Assigning a value to a text field in Selenium results in an error message stating that the element cannot be found: NoSuchElementException - "Unable to locate element

I am diving into the world of Web scraping and Python for the first time. My task involves setting the value in a text box named "rcdate" on a specific URL using Selenium, and then extracting the filtered values. When trying to run this code snippet, an ex ...

ClearCase Base encountered an error and exited with code 1 due to an IOException indicating that cleartool did not provide the expected exit code

Upon research, it was discovered that in order to execute Selenium tests from Jenkins, the recommended method is to run Jenkins using the command java -jar jenkins.war instead of as a service. The issue arises when trying to run Jenkins as a service, as i ...

Scrape embedded content within an IFrame on a webpage with Java

Currently, I am interested in crawling the dynamic content within an IFramed webpage; Unfortunately, none of the crawlers I have tested so far (Aperture, Crawl4j) seem to support this feature. The result I typically get is: <iframe id="template_cont ...

Screenshot of TestNg Report

When it comes to using TestNG for reporting, I often attach screenshots as hyperlinks to test cases using Reporter.log. However, the issue arises when these screenshot file paths are located on my local system folder. How can others access these screensh ...

Encountering the error message "java: incompatible types: java.lang.Object cannot be converted to org.testng.ISuiteResult"

While utilizing the reportNg tool to generate result reports for my automation framework, I noticed that it lacks the ability to display the testcase descriptions in the results. This led me to explore creating a custom HTML result report using the IReport ...

Using Selenium to navigate to Google and selecting the Images link, followed by clicking on the first image

Below is the code I'm working with. When I run it: Firefox opens - as expected Navigates to Google.com - as expected Types "Pluralsight logo" in the search box - as expected However, after that, I see the Google.com page with an empty search box. W ...

Decoding a JSON array containing multiple JSON objects into an ArrayList of org.json.JSONObject instances using Gson

I have a JSON string that looks like this: { "r": [ { "pic": "1.jpg", "name": "Name1" }, { "pic": "2.jpg", "name": "Name2" }, { "pic": "3.jpg", "name": "Name3" } ] } My goal is to convert it ...

Error encountered: WebDriverBackedSelenium NullPointerException

I've recently started using selenium and I'm still in the process of exploring its capabilities. Currently, I am trying to test an ajax element on a website. When I click on this element, some text appears in a specific area on the page. I have s ...

How can I create a reusable function in Java Selenium WebDriver that can be called multiple times?

@Test(priority = 0) public void platformAdminLogin() { // logging in as a platform admin using correct credentials try { driver.findElement(By.id("emailId")).sendKeys("example@example.com"); driver.findElement(By.id("password")).sen ...

What is the best way to split a string based on multiple delimiters?

Can someone help me extract the text 18-Aug-2019 14:00 from Egypt Today Last Update Time: 18-Aug-2019 14:00 (GMT)? I tried splitting at ":" as my first step, followed by splitting at " (" (essentially 2 splits), but that approach is not working. Is there a ...

"What are the necessary components to include in UserDTO and what is the reasoning behind their

Presenting the User entity: package com.yogesh.juvenilebackend.Model; import jakarta.annotation.Generated; import jakarta.persistence.*; import lombok.*; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @RequiredArgsConstructor public class ...

Display a loading spinner (circle) while fetching JSON data from a given URL

Just starting out with Android Studio and trying to fetch JSON data from a URL using Volley. It's all working fine, but I'd like to add a loading circle while retrieving the JSON data. If anyone could help me with my code: package imo.meteoir ...

When attempting to run tests with Chromedriver and Maven, a java.lang.NoSuchMethodError occurs with com.google.common.collect.ImmutableMap

Just starting out with selenium tests and currently following some tutorials on maven via YouTube. Today, I experimented with a few codes which worked fine until I encountered an "Access Denied" message while trying to search for a product on a store page ...

Obtaining Table Data Using Selenium in C# with Headless Chrome

I recently completed the automation of a website and everything was working smoothly. However, I encountered an issue when running the same automation with headless Chrome. Some table cells were showing up empty while others displayed correctly. ChromeOpt ...