Encountering a null pointer exception when launching the Chrome browser using Selenium

Hope you all are doing well.

I need assistance in resolving a null pointer issue while developing a new Selenium framework for my company. The problem arises after calling the method "StartBrowser()" from the base class in the browser class. Everything runs smoothly until "StartBrowser()", but then a null pointer exception is thrown.

Thank you in advance for your help.

{
public WebDriver driver;

public WebDriver StartBrowser() throws IOException
{
    Properties prop=new Properties();
    FileInputStream fis=new FileInputStream(System.getProperty("user.dir")+"\\src\\main\\java\\config\\config.properties");
    prop.load(fis);
    String browserName=prop.getProperty("browser");
    String LADSurl=prop.getProperty("LADSurl");
    String GADSurl=prop.getProperty("GADSurl");
    String chromeDriverPath=prop.getProperty("ChromeDriverPath");
    System.out.println(browserName);
    
    if (browserName.equalsIgnoreCase("chrome"))
    {
        System.setProperty("webdriver.chrome.driver", chromeDriverPath);
        driver=new ChromeDriver();
    }
    else if(browserName.equalsIgnoreCase("firefox"))
    {   
    }
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    return driver;
}

}

public class Base {
public static WebDriver driver;
BrowserFactory browser;
public static Properties prop;
public static String LADSurl;
public static String GADSurl;


enter code here

public static void setupPropertiesFile() throws IOException {
    Properties prop = new Properties();
    FileInputStream fis = new FileInputStream(
            System.getProperty("user.dir") + "\\src\\main\\java\\config\\config.properties");
    prop.load(fis);
    String browserName = prop.getProperty("browser");
    String LADSurl = prop.getProperty("LADSurl");
    String GADSurl = prop.getProperty("GADSurl");
    String chromeDriverPath = prop.getProperty("ChromeDriverPath");
}
public static void OpenApplication(String environment) throws IOException {
    BrowserFactory browser=new BrowserFactory();
    browser.StartBrowser();
    if (environment.equalsIgnoreCase("LADS")) {
        driver.get("www.google.com"); // Local ADS URL
    } else if (environment.equalsIgnoreCase("GADS")) {
        driver.get(GADSurl); // Global ADS URL
    } 

}

Console error: Jul 26, 2020 1:49:05 PM cucumber.api.cli.Main run WARNING: You are using deprecated Main class. Please use io.cucumber.core.cli.Main

Scenario: Create Student # src/test/resources/Features/CreateUsers.feature:3 chrome Starting ChromeDriver 84.0.4147.30 (48b3e868b4cc0aa7e8149519690b6f6949e110a8-refs/branch-heads/4147@{#310}) on port 47410 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. Jul 26, 2020 1:49:09 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFO: Detected dialect: W3C Given User is on New User page # stepDefinitions.CreateUserSteps.user_is_on_new_user_page() java.lang.NullPointerException at utils.Base.OpenApplication(Base.java:39) at stepDefinitions.CreateUserSteps.user_is_on_new_user_page(CreateUserSteps.java:38) at ✽.User is on New User page(file:///C:/Users/rgorilla/eclipse-workspace/ESA/src/test/resources/Features/CreateUsers.feature:4)

When User provide student information click Save User # stepDefinitions.CreateUserSteps.user_provide_student_information_click_save_user() Then Validate user is created successfully # stepDefinitions.CreateUserSteps.validate_user_is_created_successfully()

Answer №1

The driver instance in your base class is null because you have not assigned it.

To fix this issue, include the following line in your openApplication() method:

driver = browser.StartBrowser();

Answer №2

A null pointer exception is occurring due to the driver instance. In order to prevent this issue in your automation framework, ensure that every page is handled by the same driver instance.

To resolve this, update your code from  **public WebDriver driver;** to **static WebDriver driver;**

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

CSS: Unexpected value, received NaNrgb

I was attempting to incorporate a checkbox into a Bootstrap form that turns green when it is checked. Here is the code I used: function updateColor() { $("#check1").animate({ "background-color": "rgb(209, 231, 221)" }); } <script src="http ...

What steps can I take to address the problem of my undefined .length value?

I encountered a length error while executing line 2 in this code snippet. index.js:10 Uncaught TypeError: Cannot read property 'length' of undefined" Sample Code: <div class="formCustomerName"> <label>Name:</label> ...

Safari experiences occasional failures with pre-signed post uploads to S3 when using multipart/form-data for file uploads

Lately, I've encountered issues with pre-signed post uploads to S3 that seem to be unique to Mobile Safari browsers. Interestingly, the error has also shown up occasionally on Desktop Safari. Whenever this error occurs, it triggers a response from S3 ...

What are some of the events that can be used with a4j:ajax?

Where can I find a complete list of available events for <a4j:ajax event="..." />? The RichFaces documentation mentions "name of JavaScript event property (click, change, etc.)", but I am specifically interested in the details of this "etc." ;) On ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

The passport authentication process is malfunctioning as there seems to be an issue with the _verify function

Having an issue and could use some assistance. I am currently implementing passport in my express application. While I am able to successfully register a user, I encounter an error when trying to log in. TypeError: this._verify is not a function at Str ...

Having trouble importing Tone.js in your Next.js project?

Having trouble importing Tone in my Next.js project. Despite having Tone as a dependency, I face an issue when trying to run import * as Tone from 'tone'. Next.js shows an error stating it can't locate the module node_modules/tone/build/esm/ ...

Guide on capturing every error thrown in a Vue.JS single-page application

As I develop a web application, my goal is to effectively capture any errors that may occur throughout the entire Vue.js web app. Although I investigated the errorHandler, I discovered that it only catches errors during rendering or watching processes. Th ...

Changing a 64-bit Steam ID to a 32-bit account ID

Is there a way to convert a 64-bit Steam ID to a 32-bit account ID in Node.js? According to Steam, you should take the first 32 bits of the number, but how exactly can this be done in Node? Would using BigNumber be necessary to handle the 64-bit integer? ...

Material Angular table fails to sort columns with object values

Currently, I am in the process of developing a web application using Angular Material. One of the challenges I have encountered is displaying a table with sorting functionality. While sorting works perfectly fine on all columns except one specific column. ...

Unable to access setOnItemSelectedListener method from Spinner

After referencing a helpful post on Stack Overflow about creating spinners programmatically in Android, I encountered an issue where my setOnItemSelectedListener process was not being triggered. Despite setting up my spinner to display room choices based ...

What causes the sudden appearance of this notification window only after the user has interacted with a button on the chromedriver interface? Could it be related to Selenium

I have a python script that automates the process of opening this website using chromedriver.exe. The script is designed to click on the wallet icon at the top right corner of the page, followed by clicking on the MetaMask wallet button. Here is the code s ...

Discover the secrets within JVM's internal data structures with the Hotspot Dynamic Attach Mechanism!

As stated on the OpenJDK's website, attaching a thread to Hotspot using the Dynamic Attach API allows for collecting information about it. Despite extensive online research, I have been unable to find resources detailing how to access specific interna ...

Tips for calculating the difference between timestamps and incorporating it into the response using Mongoose

In my attendance model, there is a reference to the class model. The response I receive contains two createdAt dates. const attendanceInfo = await Attendance.find({ student: studentId, }) .populate('class', 'createdAt'); ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Using JavaScript to sort through JSON data arrays

I am dealing with a JSON data structure as shown below: var data = [ { "type": "Feature", "id": 1, "properties": { "name": "William", "categorie": 107, "laporan":"Fire", "time":1, ...

Retrieve the total number of arrays from the API, rather than fetching the actual data

I'm attempting to retrieve the total number of arrays of validators (e.g. 1038) from a JSON file using the code below, but it doesn't seem to be working as expected. Can anyone spot what's wrong with my code? let data = fetch("https://avax. ...

Learn the steps to resolve pagination issues in React. When the first page loads, ensure all data is displayed properly. Click

Here is an excerpt from my code snippet: const Inventory = () => { const [products, setProducts] = useState([]); const [pageCount,setPageCount] = useState(0); //console.log(pageCount); const [page,setPage] = useState(0); const navigate = useNa ...

Delete a designated section from a URL with the power of jQuery

I have a URL like http://myurleg.com/ar/Message.html and I need to change ar to en in it when clicked on. For example, if my current URL is: http://myurleg.com/ar/Message.html After clicking, it should become: http://myurleg.com/en/Message.html I attemp ...

Exploring the retrieval of JavaScript array elements from a ListModel within QML

Currently, I have some JavaScript data that consists of a list of objects containing other objects and arrays, which I want to append to a ListModel. This is what the structure looks like (assuming that the data is generated elsewhere and its structure sh ...