Getting java.lang.NullPointerException for selenium webdriver class - java

I am quite new to Selenium WebDriver. A java.lang.NullPointerException has been troubling me for sometime now, and I cannot understand why. Following are my classes which are quite simple actually:
suiteBase.java
package utilities.suiteBase;
import org.openqa.selenium.WebDriver;
import actions.testPage1.testPage1Actions;
import ui_map.testPage1.TestPage1UI;
public class suiteBase {
public WebDriver driver;
protected static TestPage1UI tpui = new TestPage1UI();
protected static testPage1Actions tpa = new testPage1Actions();
}
testPage1Actions.java
package actions.testPage1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.WebElement;
import utilities.suiteBase.suiteBase;
public class testPage1Actions extends suiteBase {
public WebDriver driver;
public void test(WebDriver driver){
WebElement loc1 = driver.findElement(By.xpath("id('email')"));
loc1.sendKeys("testing");
System.out.println("done...");
}
}
TestPage1.java
package testPage1;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utilities.suiteBase.BrowserOpen;
import utilities.suiteBase.suiteBase;
public class TestPage1 extends suiteBase{
public WebDriver driver;
BrowserOpen browse = new BrowserOpen();
#Parameters({ "browserType", "appURL" })
#Test(priority = 1)
public void openBrowser(String browserType, String appURL){
browse.setUp(browserType, appURL);
System.out.println("Done....");
}
#Test(priority = 2)
public void testCase1() throws InterruptedException{
driver.wait(1000);
tpa.test(driver);
}
}
I run the TestPage1.java file using XML, where I encounter following error:
java.lang.NullPointerException at
testPage1.TestPage1.testCase1(TestPage1.java:28) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
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.runSequentially(SuiteRunner.java:329) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) at
org.testng.SuiteRunner.run(SuiteRunner.java:240) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1198) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1123) at
org.testng.TestNG.run(TestNG.java:1031) at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58)
Also I have browserOpen class which I run before TestPage1, in which I declare the WebDriver
package utilities.suiteBase;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utilities.suiteBase.BrowserOpen;
public class BrowserOpen {
public WebDriver driver;
static String driverPath = "E:\\Selenium\\";
public void setUp(String browserType, String appURL) {
try {
setDriver(browserType, appURL);
} catch (Exception e) {
System.out.println("Error....." + e.getStackTrace());
}
}
#AfterClass
public void tearDown() {
driver.quit();
}
private void setDriver(String browserType, String appURL) {
switch (browserType) {
case "chrome":
driver = initChromeDriver(appURL);
break;
case "firefox":
driver = initFirefoxDriver(appURL);
break;
default:
System.out.println("browser : " + browserType
+ " is invalid, Launching Firefox as browser of choice..");
driver = initFirefoxDriver(appURL);
}
}
private static WebDriver initChromeDriver(String appURL) {
System.out.println("Launching google chrome with new profile..");
System.setProperty("webdriver.chrome.driver", driverPath + "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(appURL);
System.out.println("URL inserted");
// driver.get(appURL);
return driver;
}
private static WebDriver initFirefoxDriver(String appURL) {
System.out.println("Launching Firefox browser..");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to(appURL);
return driver;
}
}

I never used this technology before, but I see not inited elements.
public WebDriver driver;
WebDriver was not initialized.
You need to initialize them before using.
Like:
WebDriver driver = new FirefoxDriver();
Or something else. Check this out: http://www.seleniumhq.org/docs/03_webdriver.jsp
-- UPD: Exception is probably throwing at testCase1() tpa.test(WebDriver). tpa is probably null.

you are using #Parameters({ "browserType", "appURL" }) in your TestPage1 class that will come from testng.xml file . Hope your using this xml file to run your test.

When I declared - public static WebDriver driver; before #BeforeSuite
and then inside the method if we again declared as
WebDriver driver = new FirefoxDriver();
and run the script then it shows me java.lang.NullPointerException error.
Please try below code to resolve :-
driver = new Firefoxdriver();
Example -
public class LearnCheckBox {
public static WebDriver driver;
#BeforeSuite
public static void verify_SetupBrowser() throws InterruptedException
{
driver = new FirefoxDriver(); //
driver.get("https://learn.letskodeit.com/p/practice");
driver.manage().window().maximize();
Thread.sleep(2000);
}
Ashish Bind

Related

The import org.openqa.selenium.chrome cannot be resolved

On Eclipse, The error red line was showing below the ChromeDriver statement and Line 18 (WebDriver driver = new ChromeDriver). Is that code correct?
Code:
package firsttestngpackage;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
//import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class FirstTestNGFile {
public String baseUrl = "http://demo.guru99.com/test/newtours/";
String driverPath=
"C:\\Users\\manoj\\Documents\\QA\\COURSE\\ChromeDriver94\\chromedriver.exe";
//public WebDriver driver;
#Test
public void f() {
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath);
WebDriver driver = new ChromeDriver();
driver.get(baseUrl);
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
driver.close();
}
}
Yes it looks fine to me.
Additionally, you'd have to import WebDriver as well.
import org.openqa.selenium.WebDriver;
If that still did not work, I would suggest to take WebDriver driver out of #Test
Sample code :
private WebDriver driver;
public String baseUrl = "http://demo.guru99.com/test/newtours/";
String driverPath = "C:\\Users\\manoj\\Documents\\QA\\COURSE\\ChromeDriver94\\chromedriver.exe";
#Test
public void f() {
System.out.println("launching chrome browser");
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.get(baseUrl);
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = driver.getTitle();
Assert.assertEquals(actualTitle, expectedTitle);
driver.close();
}
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
// Few important imports in selenium to look.
// WebDriver interface is important for using methods
get(),getCurrentUrl(),findElement(),close(),quit() etc

Cannot instantiate class error message - in testNG

I used these two classes to execute my program. In one class i have kept all my variables, in another class i have kept the code to be executed. But I am unable to execute the code. I am getting error message stating that Cannot instantiate class
package BalajiSanthanamAcademy.MavenJava;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class CommonVariableTest {
public static WebDriver driver=null;
public String key="webdriver.chrome.driver";
public String path="C:\\Program Files\\Java\\chromedriver_win32\\chromedriver.exe";
public String baseUrl = "https://www.expedia.co.in/";
public String expUrl = "https://www.expedia.co.in/";
public String Yatra = "https://www.yatra.com/";
public String expYatra = "https://www.yatra.com/";
//yatra search
WebElement departFrom =driver.findElement(By.xpath("//input[#id='BE_flight_origin_city']"));
//Flying From class variables
public String Depature = "CJB";
public String goingTo = "MAA";
//Flying To class variables
//Declaring departure and return date
public String departureDate = "07/22/2020";
public String returnDate = "10/15/2020";
}
and below class is the one which i used to execute
package BalajiSanthanamAcademy.MavenJava;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class YatraLoginTest extends CommonVariableTest {
WebDriver driver;
#BeforeClass
public void setup()
{
System.setProperty(key,path);
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
}
#Test (priority=1)
public void setBaseURL()
{
driver.get(Yatra);
System.out.println(driver.getCurrentUrl());
try{
Assert.assertEquals(expYatra, driver.getCurrentUrl());
System.out.println("Navigated to correct webpage");
}
catch(Throwable pageNavigationError)
{
System.out.println("Didn't navigate to correct webpage");
}
}
#Test (priority=2)
public void Login() throws InterruptedException
{
driver.findElement(By.cssSelector("body.wrapper-snipe.wrapper-toucan.tenantwrapper-dom.catwrapper-home:nth-child(2) div.theme-snipe:nth-child(2) div.yatra-header.headerGrp div.wrapper div.header-container.desktop-only div.header-right-menu.menu.ftL div.settings ul.justified-menu.desktop-navs.settings-content.responsivetabshow li.list-dropdown:nth-child(1) > a.dropdown-toggle")).click();
driver.findElement(By.cssSelector("#signInBtn")).click();
WebDriverWait w =new WebDriverWait(driver,10);
w.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#id='login-input']")));
driver.findElement(By.xpath("//input[#id='login-input']")).click();
driver.findElement(By.xpath("//input[#id='login-input']")).sendKeys("balajimscit09#gmail.com");
Thread.sleep(2000L);
driver.findElement(By.cssSelector("#login-continue-btn")).click();
WebDriverWait x =new WebDriverWait(driver,10);
x.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#login-password")));
driver.findElement(By.cssSelector("#login-password")).click();
driver.findElement(By.cssSelector("#login-password")).sendKeys("Welcome-1");
driver.findElement(By.cssSelector("#login-submit-btn")).click();
}
#Test (priority=3)
public void HomepageValidation() throws InterruptedException
{
WebDriverWait Y =new WebDriverWait(driver,15);
Y.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#class='dropdown-toggle loginUserName']")));
String Wel = driver.findElement(By.xpath("//a[#class='dropdown-toggle loginUserName']")).getText();
Assert.assertEquals(Wel,"Hi Balaji");
System.out.println(Wel+" = Login details Sucessfully validated");
}
#Test (priority=4)
public void yatraSearch() throws InterruptedException
{
//Round trip tab
driver.findElement(By.xpath("//a[#class='blur_class']")).click();
Thread.sleep(3000L);
//Depart from
departFrom.click();
Thread.sleep(3000L);
departFrom.sendKeys("CJB");
Thread.sleep(3000L);
departFrom.sendKeys(Keys.ENTER);
Thread.sleep(3000L);
departFrom.getAttribute("value");
//Going To
WebElement goinTo =driver.findElement(By.xpath("//input[#id='BE_flight_arrival_city']"));
Thread.sleep(3000L);
goinTo.sendKeys(goingTo);
Thread.sleep(3000L);
goinTo.sendKeys(Keys.ENTER);
driver.findElement(By.cssSelector("#BE_flight_origin_date")).click();
Thread.sleep(3000L);
WebElement element = driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/section[1]/div[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/ul[1]/li[2]/ul[1]/li[1]/section[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/table[1]/tbody[1]/tr[2]/td[4]"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
Thread.sleep(3000L);
WebElement element1 = driver.findElement(By.xpath("//div[#class='month-box BE_flight_arrival_date']//div[1]//table[1]//tbody[1]//tr[2]//td[7]"));
Actions actions1 = new Actions(driver);
actions1.moveToElement(element1).click().build().perform();
driver.findElement(By.xpath("//span[#class='txt-ellipses flight_passengerBox travellerPaxBox']")).click();
for(int i=0;i<2;i++)
{
driver.findElement(By.xpath("//div[#class='iePasenger dflex']//div[1]//div[1]//div[1]//span[2]")).click();
driver.findElement(By.xpath("//div[#class='vertical_search_engine']//div[2]//div[1]//div[1]//span[2]")).click();
}
driver.findElement(By.cssSelector("#BE_flight_flsearch_btn")).click();
}
#Test (priority=5)
public void SearchValid() throws InterruptedException
{
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Select Origin']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Select Destination']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Depart']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Return']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//body/section[#id='flightSRP']/section/div/div/form[#id='modifySearch']/ul/li[5]/div[1]")).getAttribute("value"));
driver.findElement(By.xpath("//div[contains(#class,'result-set pr grid')]//div[2]//div[1]//div[1]//div[1]//div[4]//div[1]//div[1]//div[1]//label[1]//div[2]//i[1]")).getText();
driver.findElement(By.xpath("//section[#id='Flight-APP']//section//section//div//div//div//button")).click();
}
}
I am getting the below error message.
[RemoteTestNG] detected TestNG version 7.0.1
org.testng.TestNGException:
Cannot instantiate class BalajiSanthanamAcademy.MavenJava.YatraLoginTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.InstanceCreator.instantiateUsingDefaultConstructor(InstanceCreator.java:193)
at org.testng.internal.InstanceCreator.createInstanceUsingObjectFactory(InstanceCreator.java:113)
at org.testng.internal.InstanceCreator.createInstance(InstanceCreator.java:79)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:109)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:167)
at org.testng.TestClass.getInstances(TestClass.java:102)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:82)
at org.testng.TestClass.init(TestClass.java:74)
at org.testng.TestClass.<init>(TestClass.java:39)
at org.testng.TestRunner.initMethods(TestRunner.java:459)
at org.testng.TestRunner.init(TestRunner.java:338)
at org.testng.TestRunner.init(TestRunner.java:291)
at org.testng.TestRunner.<init>(TestRunner.java:222)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.ITestRunnerFactory.newTestRunner(ITestRunnerFactory.java:55)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:676)
at org.testng.SuiteRunner.init(SuiteRunner.java:178)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:112)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1275)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1251)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1100)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:23)
... 27 more
Caused by: java.lang.NullPointerException
at BalajiSanthanamAcademy.MavenJava.CommonVariableTest.<init>(CommonVariableTest.java:20)
at BalajiSanthanamAcademy.MavenJava.YatraLoginTest.<init>(YatraLoginTest.java:19)
... 33 more
Can you please help me how to resolve
The Root Cause is NullPointerException as shown in last few lines in your logs. The reason is this line -
public static WebDriver driver=null;
You need to create a new instance of WebDriver and assign it to the variable driver
Thank you for the co-ordination. I found the answer at last. The mistake is i have placed an web element in CommonVariableTest class, and tried to access the WebElement from YatraLoginTest class. Hence the error message wasthrown. when i removed the WebElement it is working fine.
Nullpointexception showing here that means url launched but driver instance not created to interact so to initially you have define driver driver as null

Facing Issues While Running Cross Browser Testing

Am Facing Issues While Runnig Cross Browser,
The issue is it is opening the browser but not navigating to the URL i Provided and Start the Test.
i Have Created Totally 3 Packages ,
1. Browser Configuration (package) - BrowserSetup.java (File)
2.TestCase (Package) - FinalTest.java(file)
3 Test Methods(Package) - List of All Methods for each Single Page(Files)
My Issue, if i don't import the Browsersetup.java inside the finaltest.java for Calling The Browser, it is Sucessfully running and test get passed. but When i Import the BrowserSetup.java inside the finalTest.java, it is Not Working Properly Down i have attached Both File of Code
BrowserSetup.java
package Browserconfiguration;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class Browsersetup
{
WebDriver driver;
public WebDriver setup(String browser) throws Exception
{
//Check if parameter passed from TestNG is 'firefox'
if(browser.equalsIgnoreCase("firefox"))
{
//create firefox instance
System.setProperty("webdriver.gecko.driver", "F:\\New folder\\geckodriver.exe");
driver = new FirefoxDriver();
}
//Check if parameter passed as 'chrome'
else if(browser.equalsIgnoreCase("chrome"))
{
//set path to chromedriver.exe
ChromeOptions options = new ChromeOptions();
options.setAcceptInsecureCerts(true);
options.setBinary(new File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"));
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");
//create chrome instance
driver = new ChromeDriver(options);
}
//Check if parameter passed as 'Edge'
else if(browser.equalsIgnoreCase("Edge"))
{
//set path to IE.exe
System.setProperty("webdriver.edge.driver","F:\\New folder (2)\\MicrosoftWebDriver (1).exe");
//create Edge instance
driver = new EdgeDriver();
}
else
{
//If no browser passed throw exception
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
FinalTest.java
public class FinalTest {
WebDriver driver;
#BeforeTest
public void beforeTest() throws Exception
{
Browsersetup obj = new Browsersetup();
obj.setup("chrome");
driver.get("http://xxx.xxxxxxxxxxxx.xxx/");
List<WebElement> links=driver.findElements(By.tagName("a"));
System.out.println("Total links are "+links.size());
for(int i=0;i<links.size();i++)
{
WebElement ele= links.get(i);
String url=ele.getAttribute("href");
verifyLinkActive(url);
}
}
//Finding the broken Links in the website.
private void verifyLinkActive(String linkUrl) {
try
{
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==200)
{
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
}
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)
{
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
}
} catch (Exception e) {
}
}
}
Please, Clarify Me Where My Issue i can't find it
Error:
java.lang.NullPointerException
at TestCase.FinalTest.beforeTest(FinalTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:455)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
at org.testng.TestRunner.beforeRun(TestRunner.java:529)
at org.testng.TestRunner.run(TestRunner.java:497)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
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)
Actually in FinalTestClass you're using another Webdriver, Try to do the following:
Use the driver which is returning from obj.setup("chrome");
public class FinalTest {
WebDriver driver;
#BeforeTest
public void beforeTest() throws Exception
{
Browsersetup obj = new Browsersetup();
driver = obj.setup("chrome");
driver.get("http://xxx.xxxxxxxxxxxx.xxx/");
//...........
}
Just try it and let me know if it didn't work.

What is this Error: at com.google.common.base.Preconditions.checkNotNull

I am a new automation tester, Working on sample test scripts, Need some help from you guys, I have tried to use POM and basic TestNG.
I have created 2 packages - pages and testcases.
I am getting some error when I am trying to access the "ClickJoin, Enterusername" methods from my pages packages. I had tried figuring out the issue, but was unable to get to why this error is occurring.
Below is the Error:
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull
My Code from the "pages" package:
package com.gptoday.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Login {
public WebDriver driver;
public WebDriverWait wait;
By join = By.xpath("//*[#id='members']/a[1]");
By username = By.id("username");
By password = By.id("password");
By loginButton = By.xpath("//*[#id='normallogin']/div[4]/p/input[2]");
public Login (WebDriver driver){
this.driver=driver;
}
public void ClickJoin(){
wait = new WebDriverWait(driver,10);
//driver.findElement(join).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(join)).click();
}
public void EnterUsername(){
wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(username)).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(username)).sendKeys("Test username");
System.out.println("Username Entered");
}
public void EnterPassword(){
driver.findElement(password).clear();
driver.findElement(password).click();
System.out.println("Password Entered");
}
public void ClickButton(){
wait = new WebDriverWait(driver, 10);
//driver.findElement(loginButton).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(loginButton)).click();
System.out.println("Login Button Clicked");
}
}
My Code from the "TestCases" package:
This code is of my base class.
package com.gptoday.com.gptoday.testcases;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterMethod;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Base {
public WebDriver driver;
#BeforeMethod
public void BaseSetup(){
ProfilesIni prof = new ProfilesIni();
FirefoxProfile ffProfile= prof.getProfile ("vishvesh");
ffProfile.setAcceptUntrustedCertificates(true);
ffProfile.setAssumeUntrustedCertificateIssuer(false);
String BaseUrl = "https://www.gptoday.com";
System.setProperty("webdriver.gecko.driver", "G:/Workplace/AutomationSetupFiles/Geckdriver/geckodriver.exe");
driver = new FirefoxDriver (ffProfile);
driver.get(BaseUrl);
driver.manage().window().maximize();
}
#AfterMethod
public void afterTest() {
System.out.println("Success");
}
}
**Below the the code for the test case.**
package com.gptoday.com.gptoday.testcases;
import org.testng.annotations.Test;
import com.gptoday.pages.Login;
import org.openqa.selenium.WebDriver;
public class LoginVerification extends Base {
public WebDriver driver;
public Login obj = new Login(driver);
#Test
public void Verify()
{
obj.ClickJoin();
obj.EnterUsername();
}
}
**Error:**
Success
FAILED: Verify
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:770)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:96)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:71)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:45)
at com.gptoday.pages.Login.ClickJoin(Login.java:22)
at com.gptoday.com.gptoday.testcases.LoginVerification.Verify(LoginVerification.java:16)
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:661)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
Here's the reason behind the error you are getting:
In both Login & EnterUsername methods while you defined the wait you have passed the instance of Webdriver & interval. Now whenever Selenium detects this particular type of argument Selenium treats this as FluentWait. Now when you actually implement a FluentWait you have to import those two libraries "com.google.common.base.Function" which will address the error you are facing. Of course you have to import "FluentWait" as well.
Let me know if this helps you.
By modifying the code in the "Login.Java" class.. The issue was related to driver being null as I did not extend "Base" in the "Login" class.

Page is not being driven

Can someone tell me why my page is not being driven using the code below? The page loads but the driver does not drive to click the ticketButton link. I am lost and could use some help. Thanks in advance.
package domainEntities;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ConstantsTest {
WebDriver driver;
public ConstantsTest(WebDriver driver){
this.driver = driver;
}
public WebElement ticketButton() {
WebElement ticketButton = driver.findElement(By.cssSelector("a.ticketButton"));
return ticketButton();
}
}
package test;
import domainEntities.ConstantsTest;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.junit.Assert.fail;
public class TenaciousD{
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
WebDriver driver = new FirefoxDriver();
#Test
public void TenaciousD() throws InterruptedException {
driver.get("http://tenaciousd.com");
ConstantsTest c = new ConstantsTest(driver);
c.ticketButton().click();
Thread.sleep(100000);
}
This is the error its returning:
java.lang.StackOverflowError
at java.io.FileInputStream.<init>(FileInputStream.java:56)
at java.net.SocketInputStream.<init>(SocketInputStream.java:61)
at java.net.AbstractPlainSocketImpl.getInputStream(AbstractPlainSocketImpl.java:415)
at java.net.Socket$2.run(Socket.java:875)
at java.net.Socket$2.run(Socket.java:873)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.Socket.getInputStream(Socket.java:872)
at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:85)
at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:107)
at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:184)
at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:163)
at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:132)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:186)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:151)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:640)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.openqa.selenium.remote.HttpCommandExecutor.fallBackExecute(HttpCommandExecutor.java:316)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:295)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.execute(NewProfileExtensionConnection.java:133)
at org.openqa.selenium.firefox.FirefoxDriver$LazyCommandExecutor.execute(FirefoxDriver.java:355)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:527)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:307)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByCssSelector(RemoteWebDriver.java:396)
at org.openqa.selenium.By$ByCssSelector.findElement(By.java:406)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:299)
at domainEntities.ConstantsTest.ticketButton(ConstantsTest.java:23)
Your StackOverflow issue is coming from your ticketButton() method.
public WebElement ticketButton() {
WebElement ticketButton = driver.findElement(By.cssSelector("a.ticketButton"));
return ticketButton();
}
You are returning the method instead of the element.
public WebElement ticketButton() {
WebElement ticketButton = driver.findElement(By.cssSelector("a.ticketButton"));
return ticketButton;
}

Categories