The Selenium TestNG framework is experiencing difficulty in accessing the driver object across multiple tests

I am encountering a null pointer error while attempting to run the program. The @test is unable to access the object - driver. What could be causing this error? Error -

A JavaScript warning has been issued: https://www.google.com/xjs/_/js/k=xjs.s.en_US.MHBUsB8Me90.O/m=sx,c,sb,cdos,cr,elog,hsm,jsa,r,qsm,d,csi/am=wCJGjhccAPk_IRQStxAWyAImDiA/rt=j/d=1/t=zcms/rs=ACT90oGwMPBWhsFBKoM1svJAFUVoVQRQug, line 7: mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create https://www.google.com/?gws_rd=ssl FAILED: websiteTitle

java.lang.NullPointerException
    at myPackage.TestNGforHDFC.websiteTitle(TestNGforHDFC.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)

package myPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class TestNGforHDFC {
    public WebDriver driver;
    public String urlUnderTest = "http://www.google.com";
    public String projLocation = "C:\\Users\\Nikita Agrawal\\Selenium\\geckodriver.exe";
    @BeforeTest
    public void login()
    {
        System.setProperty("webdriver.gecko.driver", projLocation);
        WebDriver driver = new FirefoxDriver();
        driver.get(urlUnderTest);
        System.out.println(driver.getCurrentUrl());
    }

    @Test
public void websiteTitle()
    {
        System.out.println(driver.getTitle());
    }
}

Answer №1

The variable driver has not been initialized in the class, but a new variable with the same name is being defined inside the login method.

Consider using:

public void login(){
    driver = new FirefoxDriver();
    ....
}

Instead of:

public void login(){
    WebDriver driver = new FirefoxDriver();
    ....
}

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

The error message indicates that the element countdown is missing or does not exist

I typically refrain from discussing topics that I'm not well-versed in (my weak spot has always been working with time and dates in javascript), but I find myself in urgent need of assistance. I've decided to use this link to showcase a countdow ...

What could be causing a case where this.props.posts is undefined in React and Redux

Recently, I attempted to follow a React and Redux tutorial on a blog. However, when working with the PostList component, I encountered an error related to the reducer binding. My main goal was simply to render the renderPost function by calling the reducer ...

Transform percentage into pixels

I'm currently utilizing this specific JavaScript range slider and my goal is to define a minimum and maximum value in pixels, rather than the default percentage range from 0 to 100. I have successfully implemented the min and max settings, now my nex ...

Tips for handling data strings using axios

In my node.js project, I am following a manual and attempting to display data obtained from jsonplaceholder app.get('/posts', async (req, res) => { const response = await axios.get('https://jsonplaceholder.typicode.com/posts'); ...

Attempting to navigate to an Activity from a Fragment

Today I am attempting to navigate from a fragment to a new activity. My objective is to have the button in my XML linked to my fragment direct me to an Activity where I can create a new client. The fragment I am working with is named Client. package com. ...

Creating a timer implementation in Node.js using Socket.IO

In the process of developing a drawing and guessing game using node.js and socket.io, I have a structure consisting of a Room class, a Game class (which is an extension of Room), and a Round class where each game consists of 10 rounds. During each round, a ...

Having trouble establishing a default route with React Router v5

I am facing an issue with setting the default route to the home page in react router v5. Despite trying several methods, I cannot get it to work as expected. Index.js import React from "react"; import ReactDOM from "react-dom"; import ...

The warning message from npm indicates a lack of permission to write to the specified directory, `/usr/local/lib

Important: For security reasons, please avoid using the suggested solution and opt for the top-voted answer instead! Query: I am attempting to execute the installation of Monaca with this command. npm install -g monaca However, immediately encountering ...

What is the method of instantiating a Selenium WebDriver instance in Node.js without initializing the browser?

Is there a way to create an instance of the selenium webdriver without launching a new browser every time? I want to keep the driver in a common place and prevent a new browser from opening with each call. The code below shows how I am currently creating a ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Store <td> in a variable

At the moment, I have a script that allows users to input an item name, along with its size, color, and other options. Each of these entries is saved as individual items with their custom specifications, such as a black t-shirt in large size. The script c ...

Error encountered while exporting TypeScript module

While I am working with Angular, TypeScript, and Gulp, my module system is CommonJS. However, I encountered an error when trying to import a module into my main.ts file: Error: Cannot find external module 'modules.ts'. Here is the snippet from ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...

Employing Selenium for extracting the id_str element

Currently, I am utilizing the Selenium library in python to scrape content from a twitter search results page: https://twitter.com/search?q=twinkie&src=typd&lang=en The Selenium library provides several functions to help identify the desired conte ...

What is the process for retrieving an array from JavaScript using the ExecuteScript function?

While returning a string may be easy, I am struggling to figure out how to return an array. Below is an example that is not working (myURLs is a global array variable): List<object> list = ((IJavaScriptExecutor)driver).ExecuteScript( ...

In order to display() or delete() a specific element based on the logged-in user, it is necessary

(function($){ $(document).ready(function() { $('.nlgchat').hide(); // hiding the chat section by default var usernames = ['Mr.EasyBB','runawayhorses','BL@DE','SirChivas']; var nameslist='&ap ...

What is the best way to retrieve a Promise from a store.dispatch within Redux-saga in order to wait for it to resolve before rendering in SSR?

I have been experimenting with React SSR using Redux and Redux-saga. While I have managed to get the Client Rendering to work, the server store does not seem to receive the data or wait for the data before rendering the HTML. server.js ...

Retrieving a string during an update request within the KendoUI datasource

I am facing an issue with my grid and data source setup. The schema.parse function is causing some unexpected behavior. Whenever I try to update or create a new row, the schema.parse() function is called again. The parameter passed to it is a string conta ...

Preserving hyperlinks while transferring text from an HTML element using JavaScript

I'm struggling to preserve links from HTML elements while copying rich text, but have been unable to achieve it despite numerous attempts. The following code represents my best effort so far, however it only copies text without maintaining the links ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...