I've the below code in Java that throws java.lang.NullPointerException at the line where I create new instance.
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Test {
public static void main(final String... args) {
Properties seleniumProperties = new Properties();
seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
System.setProperties(seleniumProperties);
WebDriver driver = new FirefoxDriver();
}
}
Line no. 14 is WebDriver driver = new FirefoxDriver(); and here's the stack trace of the exception:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.startsWith(String.java:1405)
at java.lang.String.startsWith(String.java:1434)
at java.util.jar.JarFile.isKnownNotToHaveSpecialAttributes(JarFile.java:594)
at java.util.jar.JarFile.checkForSpecialAttributes(JarFile.java:552)
at java.util.jar.JarFile.hasClassPathAttribute(JarFile.java:518)
at java.util.jar.JavaUtilJarAccessImpl.jarFileHasClassPathAttribute(JavaUtilJarAccessImpl.java:37)
at sun.misc.URLClassPath$JarLoader.getClassPath(URLClassPath.java:1186)
at sun.misc.URLClassPath.getLoader(URLClassPath.java:522)
at sun.misc.URLClassPath.getNextLoader(URLClassPath.java:484)
at sun.misc.URLClassPath.getResource(URLClassPath.java:238)
at java.net.URLClassLoader$1.run(URLClassLoader.java:365)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at Test.main(Test.java:14)
I think I found the problem. Using System.setProperties probably removes all crucial properties used by JVM. I replaced the code with System.setProperty as shown below and now it works fine.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Test {
public static void main(final String... args) {
/*
Properties seleniumProperties = new Properties();
seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
System.setProperties(seleniumProperties);
*/
System.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
WebDriver driver = new FirefoxDriver();
}
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
It works fine when I run the test class by using the all objects form PartnerLogin POM class to Test1 Class. The problem goes when I try to call login.Login(); which contains all the objects form PartnerLogin POM class method (from another class) and calling profile object right after, getting to the null pointer exception error:
java.lang.NullPointerException at page
object.PartnerNavigationDrawer.Profile(PartnerNavigationDrawer.java:30)
How can I solve this?
POM class
package pageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class PartnerNavigationDrawer {
public WebDriver driver;
public PartnerNavigationDrawer(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver = driver;
}
By Dashboard = By.cssSelector("a[href='partner_dashboard.php']");
By Profile = By.cssSelector("a[href='partner_page.php']");
public WebElement Dashboard() {
return driver.findElement(Dashboard);
}
public WebElement Profile() {
return driver.findElement(Profile);
}
}
Test Class
package com.rslsolution;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import mainTest.PartnerLoginTest;
import com.rslsolution.Base;
import pageObject.PartnerLogin;
import pageObject.PartnerNavigationDrawer;
public class Test1 extends Base{
String baseUrl = System.getProperty("user.dir");
Properties pro = new Properties();
FileInputStream fis;
WebDriver driver;
#Test
public void testMethod() throws InterruptedException, IOException
{
fis =new FileInputStream(baseUrl+"\\DataDriven\\DataDriven.properties");
pro.load(fis);
// driver = initializeBrowser();
// driver.get(pro.getProperty("appUrl"));
PartnerLoginTest partnerLogin=new PartnerLoginTest();
Thread.sleep(3000);
partnerLogin.Login();
Thread.sleep(3000);
// PartnerLogin login=new PartnerLogin(driver);
// Thread.sleep(3000);
// login.Partner_Login().click();
// Thread.sleep(3000);
// login.email().sendKeys(pro.getProperty("userName"));
// login.password().sendKeys(pro.getProperty("partnerPassword"));
// login.Login_Button().click();
PartnerNavigationDrawer navigationDrawer = new PartnerNavigationDrawer(driver);
navigationDrawer.Profile().click();
System.out.println("Checking git push command");
}
}
Error Log
java.lang.NullPointerException
at pageObject.PartnerNavigationDrawer.Profile(PartnerNavigationDrawer.java:28)
at com.rslsolution.Test1.testMethod(Test1.java:35)
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)
PartnerLogin Class
package pageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class PartnerLogin {
WebDriver driver;
public PartnerLogin(WebDriver driver) {
this.driver = driver;
}
By Partner_Login = By.xpath("/html/body/div[3]/p/a[3]/b/span");
By email = By.cssSelector("input[id='userName']");
By password = By.cssSelector("input[id='pass']");
By Login_Button = By.cssSelector("button[id='submit']");
public WebElement Partner_Login() {
return driver.findElement(Partner_Login);
}
public WebElement email() {
return driver.findElement(email);
}
public WebElement password() {
return driver.findElement(password);
}
public WebElement Login_Button() {
return driver.findElement(Login_Button);
}
}
driver is null in class Test1. I cannot see where you assign a value to it.
I am using this code and generate this error
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.MobileDriver;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
public class HandlingScrollVertical {
public static void main(String[] args) throws MalformedURLException, InterruptedException {
// TODO Auto-generated method stub
DesiredCapabilities dc= new DesiredCapabilities();
dc.setCapability(MobileCapabilityType.AUTOMATION_NAME, "Appium");
//dc.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
dc.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1.1");
dc.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
dc.setCapability(MobileCapabilityType.APP, "/home/connexis/appium/AppiumMobile/src/main/java/Apps/ApiDemos.apk");
URL url =new URL("http://127.0.0.1:4723/wd/hub");
AndroidDriver<WebElement> driver= new AndroidDriver<WebElement>(url,dc);
driver.findElementsByAccessibilityId("Animation").get(1).click();
/*WebElement info=driver.findElementsById("android:id/text1").get(1);
int x1=info.getLocation().getX();
int y1=info.getLocation().getY();
int x2=x1 /2;
int y2=y1 /2;
TouchAction a = new TouchAction((MobileDriver) driver);
a.press(info).moveTo(x1,y1).perform().release();*/
Thread.sleep(8000);
driver.quit();
}
}
Envorinment variable set :
Selenium Server standalone 2.53
Java-Client 5.0.4
Emulator
Error log:
Exception in thread "main" java.lang.ClassCastException: java.util.HashMap cannot be cast to org.openqa.selenium.WebElement
at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:397)
at io.appium.java_client.DefaultGenericMobileDriver.findElements(DefaultGenericMobileDriver.java:54)
at io.appium.java_client.AppiumDriver.findElements(AppiumDriver.java:167)
at io.appium.java_client.FindsByAccessibilityId.findElementsByAccessibilityId(FindsByAccessibilityId.java:38)
at io.appium.java_client.AppiumDriver.findElementsByAccessibilityId(AppiumDriver.java:203)
at HandlingScrollVertical.main(HandlingScrollVertical.java:33)
As pointed out by Arnaud in the comments, this has been declared as a bug and was fixed by this pull request on Axium.
Updating your appium-android-driver to a more recent version should fix it.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method copyFile(java.io.File, java.io.File) in the type FileUtils is not applicable for the arguments (java.io.File, com.gargoylesoftware.htmlunit.javascript.host.file.File)
The constructor File(String) is not visible
at DEMO.Screenshot.Homepage(Screenshot.java:37)
at DEMO.Screenshot.main(Screenshot.java:47)
Sample Code:
package DEMO;
import java.io.IOException;
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
public class Screenshot {
WebDriver driver;
public void Homepage() {
System.setProperty("webdriver.gecko.driver", "E:\\selenium_course\\geckodriver.exe");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.firefox();
capabilities.setBrowserName("firefox");
capabilities.setVersion("your firefox version");
capabilities.setPlatform(Platform.WINDOWS);
capabilities.setCapability("marionette", false);
driver = new FirefoxDriver(capabilities);
// driver=new ChromeDriver();
driver.get("https://amazon.com");
driver.manage().window().maximize();
// take screen shot and store into variable
java.io.File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// copy screen shot into local system
try {
FileUtils.copyFile(src, new File("E:\\selenium_course\\Screen\\homepage.png"));
} catch (IOException t) {
System.out.println(t.getMessage());
}
driver.close();
}
public static void main(String[] args) {
Screenshot s = new Screenshot();
s.Homepage();
}
}
You use File from com.gargoylesoftware.htmlunit.javascript.host.file, you should use File from java.io. Replace the import
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
With
import java.io.File;
//instead of using try catch at
FILEUTIL.cpy file use that exception handler at public static void main//
public static void main(String[] args) throws exception
I am facing this 'Cannot insantiate class' error on running one of my test cases in selenium webdriver using java(Using Maven project).
Below is the parent class where I defined driver and properties
package com.pvi.qa.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestBase {
public static WebDriver driver;
public static Properties prop ;
public TestBase() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("C:\\Users\\RxLogix\\eclipse-workspace\\PviIntake\\src\\main\\java\\com\\pvi\\qa\\config\\config.properties"));
prop.load(ip);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void initialization () {
String BrowserName = prop.getProperty("browser");
if(BrowserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32 (1)\\chromedriver.exe");
driver = new ChromeDriver();}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
}
Below is the test cases class which I am running through TestNG
package com.pvi.qa.testcases;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.pvi.qa.base.TestBase;
import com.pvi.qa.pages.HomePage;
import com.pvi.qa.pages.LoginPage;
public class LoginPageTest extends TestBase{
LoginPage loginPage;
HomePage homePage;
public LoginPageTest() {
super();
}
#BeforeMethod
public void setUp() {
initialization();
loginPage = new LoginPage();
}
#Test
public void logintest() {
homePage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
And below is the error I am getting -
[RemoteTestNG] detected TestNG version 6.14.3
org.testng.TestNGException:
Cannot instantiate class com.pvi.qa.testcases.LoginPageTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:423)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:336)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:125)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:190)
at org.testng.TestClass.getInstances(TestClass.java:95)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:81)
at org.testng.TestClass.init(TestClass.java:73)
at org.testng.TestClass.<init>(TestClass.java:38)
at org.testng.TestRunner.initMethods(TestRunner.java:389)
at org.testng.TestRunner.init(TestRunner.java:271)
at org.testng.TestRunner.init(TestRunner.java:241)
at org.testng.TestRunner.<init>(TestRunner.java:192)
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.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:713)
at org.testng.SuiteRunner.init(SuiteRunner.java:260)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:198)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1295)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1273)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1128)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:24)
... 25 more
Caused by: java.lang.NullPointerException
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at com.pvi.qa.base.TestBase.<init>(TestBase.java:20)
at com.pvi.qa.testcases.LoginPageTest.<init>(LoginPageTest.java:17)
... 30 more
I have tried everything but not worked for me, Please let me know why I am getting this error. Thanks
The lowest 'caused by' section points you to the underlying exception in your base class constructor: you are calling System.getProperty with a file path; that will probably return null. To me it looks like the whole call shouldn't be there, and you just want to pass the file path to the FileInputStream constructor (or read it from a system property with some key)
Looking at the code, I understand the issue is in the constructor of the base class.
LoginPageTest calls super() which invokes TestBase.
FileInputStream needs a file path. I suspect FileInputSteam object created is coming as null.
Why are you calling System.getProperty? Is the config.properties file available?
Just Remove System.getproperty from your base class. Use this lines of code
prop = new Properties();
FileInputStream ip = new FileInputStream(("C:\\Users\\RxLogix\\eclipse-workspace\\PviIntake\\src\\main\\java\\com\\pvi\\qa\\config\\config.properties"));
prop.load(ip);
Getting this error while running a simple test.
> java -version
java version "1.8.0_102"
> compiler version javac -version
javac 1.8.0_102
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/openqa/selenium/WebDriver : Unsupported major.minor version 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2615)
at java.lang.Class.getMethod0(Class.java:2856)
at java.lang.Class.getMethod(Class.java:1668)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Here's the code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CustomerSignUpTest {
public static void main(String[] args) {
WebDriver selenium = new ChromeDriver();
selenium.get("http://www.cvs.com");
WebElement signuplink = null;
signuplink.findElement(By.partialLinkText("singup"));
WebElement Clicklink = null;
Clicklink.click();
I am getting "Access Denied" error after website open. Still try if below code works for you -
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.IOException;
public class test {
#SuppressWarnings("null")
public static void main(String[] args) {
String Browser_Full_path = Driver.APP_PATH + "\\Support JAR\\32 bit\\BrowserDrivers\\" + "chromedriver.exe";
System.out.println(" browser full path => " + Browser_Full_path);
System.setProperty("webdriver.chrome.driver", Browser_Full_path);
ChromeDriverService cds = ChromeDriverService.createDefaultService();
try {
cds.start();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.cvs.com");
WebElement signuplink = null;
signuplink.findElement(By.partialLinkText("signup"));
WebElement Clicklink = null;
Clicklink.click();
}
}
Had same issue. Removed older Java JDKs from the system, set to build with Java8 and worked like magic.