This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am getting Java Null Pointer Exception when trying to run the below code. The test gets failed before the Web page even loads completely.
I have increased the page load timeout and Implicit wait time, but still that didn't work. The same web page is getting loaded within 4 seconds when directly launched through browser. Please find the below code:
//Loginpagetest.java
Loginpage loginpage = new Loginpage();
public LoginPageTest() throws IOException {
super();
}
#BeforeMethod
public void setup(){
initialize();
}
#Test(priority=1)
public void loginPageTitleTest(){
String actualTitle = loginpage.validateLoginPageTitle();
String expectedTitle = "#1 Free CRM software in the cloud for sales and service";
Assert.assertEquals(actualTitle,expectedTitle);
}
//TestBase.java
public void initialize(){
String browsername = prop.getProperty("browser");
if(browsername.equals("chrome")){
System.setProperty("webdriver.chrome.driver","C:\\Users\\Pranaykumar\\Downloads\\"chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver(options);
}else if(browsername.equals("mozilla")){
System.setProperty("webdriver.gecko.driver","E:\\geckodriver.exe");
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
//driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
//Loginpage.java
public String validateLoginPageTitle(){
return driver.getTitle();
}
//Console
[RemoteTestNG] detected TestNG version 6.14.3
Starting ChromeDriver 2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387) on port 42802
Only local connections are allowed.
[1548934220.587][WARNING]: Timed out connecting to Chrome, retrying...
Jan 31, 2019 5:00:25 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
FAILED: loginPageTitleTest
java.lang.NullPointerException
at com.crm.qa.pages.Loginpage.validateLoginPageTitle(Loginpage.java:37)
at com.crm.qa.testcases.LoginPageTest.loginPageTitleTest(LoginPageTest.java:30)
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)
The likely scenario is that you are creating a new instance of the driver inside your Loginpage page object instead of passing the existing instance so it's not initialized... thus the NPE.
Looks like this is not timeout issue, It’s showing NullPointerException. Maybe driver is null.
Check your chrome driver path is correct or not.
‘FAILED: loginPageTitleTest
java.lang.NullPointerException
at com.crm.qa.pages.Loginpage.validateLoginPageTitle(Loginpage.java:37)’
If it’s timeout issue, you should get TimeoutExcepton.
Can you please try to wait explicitly for an specific object in initialize() function and after the driver.get(prop.getProperty("url")) line as below code :
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(objectShouldPresent)));
Kindly remove double quotes(") before chromedriver_win32
System.setProperty("webdriver.chrome.driver","C:\\Users\\Pranaykumar\\Downloads\\"chromedriver_win32\\chromedriver.exe");
Related
New to SO & test automation & selenium. I got introduced to gitpod while attempting https://www.lambdatest.com/certifications/.
I'm stuck trying to run the below simple code snippet in side Gitpod.
package project.maven.selenium;
import org.openqa.selenium.WebDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class WebDriverManagerDemo {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = WebDriverManager.chromedriver().create();
// Navigate to the demoqa website
driver.get("https://www.lambdatest.com/selenium-playground/checkbox-demo");
Thread.sleep(3000);
driver.quit();
}
}
Couldn't find a way pass the error below,
Exception in thread "main" io.github.bonigarcia.wdm.config.WebDriverManagerException: There was an error creating WebDriver object for Chrome at io.github.bonigarcia.wdm.WebDriverManager.instantiateDriver(WebDriverManager.java:1775) at io.github.bonigarcia.wdm.WebDriverManager.create(WebDriverManager.java:425) at project.maven.selenium.WebDriverManagerDemo.main(WebDriverManagerDemo.java:9) 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:77) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
Can someone please point out what I'm doing wrong here?
Researched hours but Selenium on Gitpod is not much of a topic, read the getting started guide with Gitpod too, to find a resolution to my problem but no luck before posting here.
Below line of code is incorrect:
WebDriver driver = WebDriverManager.chromedriver().create();
Try the below code:
public static void main(String[] args) throws InterruptedException {
// below line is used to setup chromedriver using WDM
WebDriverManager.chromedriver().setup();
//initialize the driver object
WebDriver driver = new ChromeDriver();
// Navigate to the demoqa website
driver.get("https://www.lambdatest.com/selenium-playground/checkbox-demo");
Thread.sleep(3000);
driver.quit();
}
I used cloudant-client-1.0.0.jar to make a test to check the connection to cloudant server as:
import com.cloudant.client.api.CloudantClient;
import com.cloudant.client.api.Database;
public class test {
private CloudantClient client=null;
public CloudantClient connect(){
client=new CloudantClient("xxx", "xxx", "xxx");
System.out.println("Connection successful! "+client.getBaseUri());
return client;
}
public Database getDb(String dbName){
Database db=connect().database(dbName, true);
System.out.println("Datase avaible - "+db.getDBUri());
return db;
}
public static void main(String[] args){
new test().getDb("_user");
}
}
However, the system shows errors:
Exception in thread "main"
java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpEntityEnclosingRequestBase
at connection.test.connect(test.java:13)
at connection.test.getDb(test.java:21)
at connection.test.main(test.java:30)
Caused by:
java.lang.ClassNotFoundException: org.apache.http.client.methods.HttpEntityEnclosingRequestBase
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 3 more
How to fix it?
You're missing a dependency for the library, Apache http client. However you should use Maven, gradle or a similar build tool which understands Maven repositories. You should also look at upgrading to 2.4.1, it contains numerous improvements and bug fixes.
I tried to execute this Selenium Script,
public class FirePath_Ex {
public static void main(String[] args)
{// TODO Auto-generated method stub
WebDriver d=new FirefoxDriver();
d.get("https://facebook.com");
d.findElement(By.xpath(".//*[#id='email']")).sendKeys("dhhfdssd");
d.findElement(By.id("pass")).sendKeys("sjfsdfj");
}
}
it shows the error below after closing FireFox,
Exception in thread "main"
org.openqa.selenium.remote.UnreachableBrowserException: Error
communicating with the remote browser. It may have died.
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 02:56:46'
System info: host: 'Admin-PC', ip: '192.168.0.101', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version:
'1.7.0-ea'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:589)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:445)
at org.openqa.selenium.By$ByXPath.findElement(By.java:358)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:340)
at FirePath_Ex.main(FirePath_Ex.java:13)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 [/127.0.0.1] failed: Connection refused: connect
How do I resolve this?
Try to add this below code and replace the path of firefox exe with your absolute path:-
System.setProperty("webdriver.firefox.bin", "C:\\firefox.exe");
So your code should be like:-
public class FirePath_Ex {
public static void main(String[] args)
{// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin", "C:\\firefox.exe");
WebDriver d=new FirefoxDriver();
d.get("https://facebook.com");
d.findElement(By.xpath(".//*[#id='email']")).sendKeys("dhhfdssd");
d.findElement(By.id("pass")).sendKeys("sjfsdfj");
}
}
Hope it will help you :)
This was driving me crazy for quite a bit.
For me, simply re-instantiating it solved the problem some of the time. (like below). However, 95% of the time it's because my selenium version is not compatible with the firefox version. The documentation for supported version is not easy to parse, nor does it contain an exhaustive list. Sometimes it takes some trail and error.
public FirefoxWebPageReader firefoxWebPageReader() {
return forceInit(3);
}
private FirefoxWebPageReader forceInit(final int tries) {
if (tries == 0) {
throw new RuntimeException("Can not initialize Firefox reader");
}
try {
final String binaryPath = environment.getProperty("crawler.firefox.path");
return new FirefoxWebPageReader(binaryPath);
} catch (WebDriverException e) {
LOGGER.error("Error occurred when building FirefoxWebPageReader, tries left: " + (tries - 1), e);
return forceInit(tries - 1);
}
}
The probable reason may be the incompatibility between the browser and the chromedriver, so installing the updated chromedriver or updating chrome might help
I am running selenium test cases in a ubuntu server which basically runs testcases in both firefox and chrome.
Firefox launches and test cases run successfully but chrome throws exception:
*****below is the snippet of the stacktrace:*****
Starting ChromeDriver (v2.8.240825) on port 21549
PAC support disabled because there is no system implementation
Test IntegrationTest.AdminUserelementscheck failed:
org.openqa.selenium.WebDriverException: chrome not reachable
(Driver info: chromedriver=2.8.240825,platform=Linux 2.6.32-431.el6.x86_64 x86_64) (WARNING: The server did not provide any stacktrace information)
[error] Command duration or timeout: 20.83 seconds
Hi Below is the small snippet of my code :
public class IntegrationTest {
private static final String configFile="test.properties";
private final String FIREFOX="firefox";
private final String CHROME="chrome";
private final String PHANTOMJS="phantomjs";
private final String BROWSERNAME="browser";
private static Properties props = new Properties();
public WebDriver webDriver;
private static Configuration additionalConfigurations;
#BeforeClass
public static void setUp() throws IOException, SQLException{
props.load(IntegrationTest.class.getResourceAsStream("/" + configFile));
}
#test
public void AdminUserelementscheck() throws SQLException, IOException {
String[] browsers = props.getProperty(BROWSERNAME).split(",");
System.out.println("Number of browsers specified in conf:"+props.getProperty(BROWSERNAME));
for(String browser:browsers){
System.out.println("Browser currently processing:"+browser);
if(browser.equalsIgnoreCase(FIREFOX))
webDriver = new FirefoxDriver();
else if(browser.equalsIgnoreCase(CHROME))
webDriver = new ChromeDriver();
else
webDriver = new PhantomJSDriver();
running(testServer(3333,fakeApplication()),webDriver, new Callback<TestBrowser>() {
********* LOGIN AND ASSERTION STATMENTS*******************
browser.quit()
}
});
}
This would be because Chrome is also making use of unix containers in order to run. If you want this to run within docker, pass the docker run command
--privileged
Otherwise you can start Chrome with
--no-sandbox
I have encoutered similar problem. I am running my Selenium tests locally and "webdriver exception chrome not reachable" error suddenly showed up.
The problem was that I already had too much tabs in my regular chrome browser. After getting frustrated I have closed few tabs and suddenly it worked. I am not sure if there is a certain limit of tabs, but if somebody encounters same problem, give it a try.
Your chrome driver seems to be old. Try downloading latest as of date from below and report back if you get any new errors.
http://chromedriver.storage.googleapis.com/index.html?path=2.14/
Also ensure that PATH environment variable has the path to chromedriver.
I was trying to read through the mails in my gmail account using java mail API. This is the code:
import java.util.*;
import java.io.*;
import java.awt.*;
import javax.mail.*;
import javax.mail.search.FlagTerm;
import javax.mail.Flags.Flag;
public class MailPharser {
/**
* #param args
*/
public void mailRead()
{
Folder inbox;
// TODO Auto-generated method stub
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com","<mailid#gmail.com>", "<password>");
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
}
catch (Exception ex)
{ System.out.println("Error caught"); ex.printStackTrace(); }
}
public static void main(String[] args) {
MailPharser mp = new MailPharser();
mp.mailRead();
}
}
While running, i am getting the below error:
javax.mail.MessagingException: Connection reset;
nested exception is:
java.net.SocketException: Connection reset
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at MailPharser.mailRead(MailPharser.java:26)
at MailPharser.main(MailPharser.java:40)
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(Unknown Source)
at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:113)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:111)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:637)
... 4 more
I added trace and see that the connect call is failing. Am i doing anything wrong? any help would do. thanks in advance...
It's probably a network problem unrelated to JavaMail, e.g., a proxy or firewall between you and Gmail.
If you want to find out whether it's your code that's broken or the network that's broken, you can test using the code that comes with JavaMail. If the JavaMail code works, then you know there's something wrong with your code, and you can use the JavaMail code in the FAQ to improve your code.
If you discover that it's a network problem, the JavaMail FAQ also has tips for debugging it further.