Nullpointer Exception in webdriver, driver is null - selenium-webdriver

I am a newbie in selenium java and trying to run test case by calling methods from another class in a framework. Methods are defined in a different class. The issue is that for first instance, the driver is found (Firefox driver) but when a method from another class is called, the driver is null.
Below is the code snippet:
public class ActionDriver {
WebDriver driver;
public ActionDriver(WebDriver driver){
this.driver = driver;
}
public void type(By loc, String value) {
driver.findElement(loc).sendKeys(value);
}
}
NPE comes for the above line of code for driver for second instance when method is called from the WebAction class. driver.findElement(loc).sendKeys(value);
Second class is :
public class WebActions {
WebDriver driver;
ActionDriver ad = new ActionDriver(driver);
SizeChartTemplate sct = new SizeChartTemplate();
public void TypeTemplateName(){
ad.type(jsct.Template_Name, "Men's Vest");
}
}
NPE is for the above line of code at ad.
Test Case:
public class LoginToJcilory extends OpenAndCloseBrowser {
#Test
public void logintojcilory() throws BiffException, IOException, InterruptedException{
WebActions wa = new WebActions();
System.out.println("Entered login to jcilory block");
ActionDriver actdrvr = new ActionDriver(driver);
JciloryLoginPage jclp = new JciloryLoginPage();
JcilorySizeChartTemplate jsct = new JcilorySizeChartTemplate();
String username = actdrvr.readExcel(0, 1);
String password = actdrvr.readExcel(1, 1);
System.out.println(username);
System.out.println(password);
actdrvr.type(jclp.Username, username);
actdrvr.type(jclp.Password, password);
actdrvr.click(jclp.LoginButton);
Thread.sleep(2000);
driver.get("http://qacilory.dewsolutions.in/JCilory/createSizeChartTemplate.jc");
wa.TypeTemplateName();
}
NPE comes for wa element in the above code.
Below is the error:
FAILED: logintojcilory
java.lang.NullPointerException
at Config.ActionDriver.type(ActionDriver.java:40)
at Config.WebActions.TypeTemplateName(WebActions.java:17)
at Test.LoginToJcilory.logintojcilory(LoginToJcilory.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.access$000(SuiteRunner.java:37)
at org.testng.SuiteRunner$SuiteWorker.run(SuiteRunner.java:368)
at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
===============================================
Test run on FIREFOX
Tests run: 1, Failures: 1, Skips: 0
===============================================
OpenAndCloseBrowser:
public class OpenAndCloseBrowser {
protected WebDriver driver;
#Parameters({"browser","baseURL"})
#BeforeClass
public void openBrowser(String browser,String baseURL){
if(browser.equalsIgnoreCase("firefox")){
driver=new FirefoxDriver();
}
else if(browser.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\driver\\chromedriver.exe");
driver=new ChromeDriver();
}
else if(browser.equalsIgnoreCase("ie")){
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\driver\\IEDriverServer.exe");
DesiredCapabilities caps=new DesiredCapabilities();
caps.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver=new InternetExplorerDriver(caps);
}
else{
driver=new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get(baseURL);
}
#AfterClass
public void closeBrowser(){
//driver.quit();
}
}
I guess there is an issue with the way i am defining the driver in these classes. Any help is resolving the issue is appreciated.

Your driver is null in ActionDriver.type() because it was null when it was passed into the constructor from WebActions. OpenAndCloseBrowser is creating a WebDriver instance, but assigning to a DIFFERENT (local) driver variable. You should learn more about variable scoping in Java...this isn't a Selenium/Webdriver issue.

You probably don't need an answer anymore, but this issue has quite the views, so just for completeness.
I usually have a global driver variable in my test class and I instantiate it like this, so it's available for every test.
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
Just add this to your test class (adapt driver path) and the driver is instantiated before the test.

Related

Cucumber #Before hook runs twice #After once

to all.
Curently writing a little BDD Test automation framework, using Java11+Junit5+Cucumber+Selenium, build tool: Graddle. Created a little test for validating Google title. When starting test, using Test task in Graddle or running CucumberRunner class, in both cases getting the same result: two times #Before method is executed, once #After method is executed and one browser windows is staying open. After added one more test, the same situation, only 4 browsers are opened, 2 of them are closing. Can anyone help with this situation?
Link to repository
After some watching of logs saw, that, seems, #Before is not executed twice, but Driver class is initialized twice, but why it happens no idea for now...
My code for now:
CucumberRunner.java:
#RunWith(Cucumber.class )
#CucumberOptions(
features = "src\\test\\java\\features",
glue = {"steps", "utils"},
tags = "#smoke")
public class CucumberRunner {
}
Driver.java:
public class Driver {
private WebDriver driver;
public Driver(){
driverInitialization();
}
private void driverInitialization(){
System.setProperty("webdriver.chrome.driver", "D:\\Soft\\selenium-drivers\\chromedriver.exe");
System.out.println("Starting driver.");
var browserName = "chrome";
switch (browserName.toLowerCase()){
case "chrome":
System.out.println("Starting chrome");
driver = new ChromeDriver();
System.out.println("Before break.");
break;
case "firefox":
driver = new FirefoxDriver();
break;
default:
throw new NotFoundException("Browser not found: " + browserName);
}
}
public WebDriver getDriver(){
return driver;
}
public WebDriverWait getWebDriverWait(){
return new WebDriverWait(driver, 120);
}
public void terminateDriver(){
System.out.println("Terminating driver.");
if (driver != null) {
driver.close();
driver.quit();
}
}
}
Hooks.java:
public class Hooks {
private Driver driver;
#Before
public void setup(){
System.out.println("In the Setup method.");
driver = new Driver();
}
#After
public void tearDown(){
System.out.println("In the TearDown method.");
driver.terminateDriver();
}
}
I think your Hook Class should be like this As You Are Using selenium-picocontainer DI.
public class Hooks {
private Driver driver;
public Hooks(Driver driver) {
this.driver = driver;
}
#Before
public void setup(){
System.out.println("In the Setup method.");
}
#After
public void tearDown(){
System.out.println("In the TearDown method.");
driver.terminateDriver();
}
}

Getting NullPointeException while running the Selenium test script

I am getting the NullPointerException after executing the below testng test script. After launching the URL when it comes inside the test script method then, it is throwing the exception. Can you please help me out in this.
(Object Repo) LakesAndMountainsHomePage.java :-
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.actitime.genericlib.WebDriverCommonLib;
public class LakesAndMountainsHomePage extends WebDriverCommonLib{
WebDriver driver;
public LakesAndMountainsHomePage(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath= "//*[#id='the-main-menu']//*[contains(text() , 'LAKES &
MOUNTAINS')]")
WebElement LandM;
public WebElement LandMHeader()
{
System.out.println("came inside the method");
//LandM.isDisplayed();
return LandM;
}
}
BaseTest.java:-
public abstract class BaseTest {
ExcelLib eLib;
WebDriverCommonLib wLib;
WebDriver driver;
HomePage homepage;
#BeforeClass
public void baseBeforeClass()
{
eLib = new ExcelLib();
wLib = new WebDriverCommonLib();
driver=Driver.getBrowser();
driver.manage().window().maximize();
System.out.println("Browser is launched");
}
#BeforeMethod
public void launchURL()
{
wLib.homePage();
//loginPage.loginToAPP();
System.out.println("Navigated to the URL");
}
}
Testscript:-
public class LakesAndMountainsHomePageTest extends BaseTest{
LakesAndMountainsHomePage lm = new LakesAndMountainsHomePage(this.driver);
//TC TC131409 [New Lakes & Mountains Tab] : Verify New Lakes & Mountains
Tab is displayed in header.
#Test(priority=0)
public void lakesAndMountainsHeader()
{
boolean a= lm.LandMHeader().isDisplayed(); //getting exception here
if(a==true)
{
System.out.println("Lakes And Mountains tab is present in the HomePage");
}
else
{
System.out.println("Lakes And Mountains tab is not present in the
HomePage");
}
lm.LandMHeader().click();
System.out.println("It has clicked the tab");
}
}
And below is the exception stack trace:-
below is the exception stacktrace:-
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy9.isDisplayed(Unknown Source)
at com.acttime.usertest.LakesAndMountainsHomePageTest.lakesAndMountainsHeader(LakesAndMountainsHomePageTest.java:27)
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)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:669)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:877)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1201)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:776)
at org.testng.TestRunner.run(TestRunner.java:634)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:425)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:420)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:385)
at org.testng.SuiteRunner.run(SuiteRunner.java:334)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1318)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1243)
at org.testng.TestNG.runSuites(TestNG.java:1161)
at org.testng.TestNG.run(TestNG.java:1129)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
I am getting the NullPointerException after executing the below testng test script. After launching the URL when it comes inside the test script method then, it is throwing the exception. Can you please help me out in this.
This instantiation is illegal.
LakesAndMountainsHomePage lm = new LakesAndMountainsHomePage(this.driver);
It is the root cause of Null pointer exception.
Move this statement to BaseTest class, create a class field and instantiate inside #BeforeClass method . Also, remove this operator.
Well i'am unable to see the implementation of a driver class specifying the type of driver(firefox,chrome,IE) being initialized.

Selenium :UnreachableBrowserException is shown in chromeDriver with testNG

When I run the following code, below error is showing : org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
The chrome browser is not getting launched.
//baseClass.java:
public class BaseClass {
//ThreadLocal will keep local copy of driver
public static ThreadLocal<RemoteWebDriver> dr = new ThreadLocal<RemoteWebDriver>();
#BeforeTest
//Parameter will get browser from testng.xml on which browser test to run
#Parameters("myBrowser")
public void beforeClass(String myBrowser) throws MalformedURLException{
try {
RemoteWebDriver driver = null;
if(myBrowser.equals("chrome")){
DesiredCapabilities capability = new DesiredCapabilities().chrome();
capability.setBrowserName("chrome");
capability.setPlatform(Platform.WINDOWS);
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
else if(myBrowser.equals("firefox")){
DesiredCapabilities capability = new DesiredCapabilities().firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WINDOWS);
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
//setting webdriver
setWebDriver(driver);
getDriver().manage().window().maximize();
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}catch (Exception ex){
System.out.println(ex.toString());
}
}
public WebDriver getDriver() {
return dr.get();
}
public void setWebDriver(RemoteWebDriver driver) {
dr.set(driver);
}
#AfterClass
public void afterClass(){
getDriver().quit();
dr.set(null);
}
}
You have to set the system property for chrome/gecko driver before initializing the RemoteWebDriver. Something like,
if(myBrowser.equals("chrome")){
DesiredCapabilities capability = new DesiredCapabilities().chrome();
capability.setBrowserName("chrome");
capability.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver\\chromedriver.exe");
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}
else if(myBrowser.equals("firefox")){
DesiredCapabilities capability = new DesiredCapabilities().firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.gecko.driver", "C:\\geckodriver\\geckodriver.exe");
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
}

Selenium Grid running tests in parallel

Currently, I have a Selenium grid setup, with 1 local hub and 2 local nodes. The hub is capable of distributing the tests to run in parallel and distribute it over to the nodes. I am running the tests in parallel.
The following is the base test
public abstract class BaseTest
{
String testFolder;
String testName;
protected String envName;
protected Configuration config;
protected String host;
protected RemoteWebDriver driver;
protected String proxy;
protected SomeData someData;
protected SomeController someController;
public BaseTest() {
}
public BaseTest( String testFolder, String testName)
{
this.testFolder = testFolder;
this.testName = testName;
this.envName = System.getProperty("config");
this.proxy = System.getProperty("proxy");
config = this.envName;
}
#BeforeMethod
public void startTest(Method testMethod) {
LOG.info("Starting test: " + testMethod.getName());
try {
this.someData = new SomeData();
this.driver = WebDriverSetup.getDriver();
this.someController = new someController(this.driver, this.someData);
driver.navigate().to("https://" + this.host);
} catch (MalformedURLException e) {
System.out.println("MalformedURLException");
}
}
#AfterMethod
public void closeWindow() {
driver.close();
driver.quit();
}
}
The following is the class to get the RemoteWebDriver:
public class WebDriverSetup {
public static RemoteWebDriver getDriver() throws MalformedURLException{
String SELENIUM_HUB_URL = "http://localhost:4444/wd/hub";
ThreadLocal<RemoteWebDriver> remoteWebDriver = null;
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
String proxy = System.getProperty("proxy");
if (proxy != null && !proxy.isEmpty()) {
System.out.println("Using proxy: " + proxy);
capabilities.setCapability(CapabilityType.PROXY, proxy);
}
try {
remoteWebDriver = new ThreadLocal<RemoteWebDriver>();
remoteWebDriver.set(new RemoteWebDriver(new URL(SELENIUM_HUB_URL),
capabilities));
} catch (MalformedURLException e) {
System.out.println("Tackle Issue with RemoteDriverSetup");
}
remoteWebDriver.get().manage().window()
.setSize(new Dimension(2880, 1524));
remoteWebDriver.get().manage().timeouts()
.pageLoadTimeout(10, TimeUnit.SECONDS);
remoteWebDriver.get().manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
return remoteWebDriver.get();
}
}
My test suite is like :
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Multiple Tests Suite" verbose="1" parallel="methods">
<test name="Test1">
<classes>
<class name="com.itesteverything.qa.Tests"></class>
</classes>
</test>
</suite>
Tests are like :
public class Tests extends BaseTest {
#Parameters({"testName", "env" })
public Tests( #Optional String testName, #Optional String env ) {
super( null, testName, null, env );
}
#BeforeMethod
public void setup() throws Exception {
//setSomeData
}
public void test1() throws Exception {
use driver from super
use someData from super
use someController is using the driver from super
}
public void test2() throws Exception {
use driver from super
use someData from super
use someController is using the driver from super
}
While running these tests, I get the following errors
Build info: version: '2.44.0', revision: '76d78cf323ce037c5f92db6c1bba601c2ac43ad8', time: '2014-10-23 13:11:40'
Driver info: driver.version: RemoteWebDriver
org.openqa.selenium.remote.SessionNotFoundException: Session ID is null. Using WebDriver after calling quit()?
Build info: version: '2.44.0', revision: '76d78cf323ce037c5f92db6c1bba601c2ac43ad8', time: '2014-10-23 13:11:40'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:572)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:393)
at org.openqa.selenium.By$ById.findElement(By.java:214)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:59)
at com.sun.proxy.$Proxy25.sendKeys(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:673)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:842)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1166)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
TEST FAILED: test2
FAILED REASON: Session ID is null. Using WebDriver after calling quit()?
Is it something anyone aware of?
Thanks in advance!
Do not set driver in the base class, do not have driver property at all. The same instance is being overridden by different threadlocal drivers.
Any time you want to run your test, refer to WebDriverSetup.getDriver() in your test method itself and in your after/before methods.
#AfterMethod
Is running after each method.
And U run's only one setup. So after first method U close and it is closed as shows stack trace.

Getting driver value as null in selenium web driver for appium mobile automation testing

private WebDriver driver;
#BeforeMethod
public void setUp() throws Exception {
// set up appium
BasicConfigurator.configure();
File appDir = new File("This PC\\GT-I9100\\Phone\\360");
File app = new File(appDir, "app-release.apk"); //my case “demo1.apk”
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("device","Android");
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability(CapabilityType.VERSION, "4.2");
capabilities.setCapability(CapabilityType.PLATFORM, "WINDOW");
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("app-package", "app-release.apk"); //my case com.gorillalogic.monkeytalk.demo1
capabilities.setCapability("app-activity", "Login"); //my case RootActivity
driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
#AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void loginTest() throws Throwable
{
System.out.println("Hello");
System.out.println(driver);
setUp();
}
#Test
public void formTest() throws InterruptedException
{
System.out.println("Hello");
System.out.println(driver);
/*Getting driver value as null in selenium web driver for appium mobile automation testing
Getting driver value as null.
Used device name then also i am getting null value
I have connected my real device.*/
Add a try/catch block when instantiating the AndroidDriver() ...
Maybe there is something wrong there. Try this code
new DesiredCapabilities();
DesiredCapabilities capabilities = DesiredCapabilities.android();
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
capabilities.setCapability(MobileCapabilityType.BROWSER_NAME,"Chrome");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,"0123456789ABCDEF");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,"4.4");
try
{
linker = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AndroidDriver(linker, capabilities);
driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
}
catch (MalformedURLException e)
{
System.out.println("URL init error");
}
Cheers

Resources