NullPointerException in my code. How to deal with it - selenium

I've written my code in Java using Selenium. When I run the code, it's throwing a NullPointerException. Check the exception below
Exception in thread "main" java.lang.NullPointerException
at AdminInterface.loginApplication(AdminInterface.java:17)
at AdminInterface.main(AdminInterface.java:29)
My code is as follows:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class AdminInterface {
public WebDriver driver;
public void launchApplication() throws Exception
{
System.setProperty("webdriver.ie.driver", "C:\\Users\\rprem\\Downloads\\IEDriverServer_x64_3.4.0\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.gcrit.com/build3/admin/");
}
public void loginApplication(String Username, String Password)
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tbd1")).click();
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args)
{
AdminInterface obj = new AdminInterface();
obj.loginApplication("admin", "admin#123");
}
}

You are seeing a NullPointerException because from main() you are trying to access the loginApplication() method right in the begining, which requires an active instance of the WebDriver i.e. the driver to findElement(By.name("username")); & findElement(By.name("password")); and perform sendKeys() method on the HTML DOM.
The solution would be to first access the launchApplication() method so you have an active instance of driver and IE Browser. Next you can access loginApplication() method.
Here is your working code block:
package demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Q45474353_NPE
{
public WebDriver driver;
public void launchApplication()
{
System.setProperty("webdriver.ie.driver", "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.get("https://www.gcrit.com/build3/admin/");
}
public void loginApplication(String Username, String Password)
{
driver.findElement(By.name("username")).sendKeys(Username);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.id("tbd1")).click();
}
public void closeBrowser()
{
driver.close();
}
public static void main(String[] args)
{
Q45474353_NPE obj = new Q45474353_NPE();
obj.launchApplication();
obj.loginApplication("admin", "admin#123");
obj.closeBrowser();
}
}

Related

Can't able to call method from multiple classes in selenium webdriver

I am trying access method from two classes in another class but only one class method is called. during call of another class method it gives NullpointerException error. Please give me solution.
Code is here--->
Setup class-->
package BasePOI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Setup {
public WebDriver driver;
public void Websiteopen() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("url");
}
public Setup(WebDriver driver){
this.driver=driver;
}
}
Login page object class--->
package BasePOI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPOI {
public WebDriver driver;
//home
By home_login=By.linkText("Login");
By about_us=By.linkText("About Us");
//login
By counselor=By.id("counselor_login");
By user=By.id("user_login");
By username=By.id("username");
By password=By.id("password");
By Login=By.name("Login");
By create_account=By.name("Login");
By Logout=By.linkText("Logout");
public LoginPOI(WebDriver driver){
this.driver=driver;
}
public void click_Login_button(){
try {
driver.findElement(home_login).click();
}
catch (Exception e)
{
System.out.println(e);
}
}
public void click_Login_counselor(){
driver.findElement(counselor).click();
}
public void click_Login_user(){
driver.findElement(user).click();
}
public void Enter_login_data(String uname,String pwd){
driver.findElement(username).clear();
driver.findElement(username).sendKeys(uname);
driver.findElement(password).clear();
driver.findElement(password).sendKeys(pwd);
}
public void click_Login(){
driver.findElement(Login).click();
}
}
Now i am calling both classes method in another class
Login functionlity class--->
package Functionlity;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import BasePOI.LoginPOI;
import BasePOI.Setup;
public class Login {
public WebDriver driver;
#Test
public void openwebsite() throws InterruptedException{
Setup a= new Setup(driver);
a.Websiteopen();
Thread.sleep(10000);
LoginPOI b=new LoginPOI(driver);
b.click_Login_button();
}
}
Here website method is running but click_Login_button method gives me
errorerror--->
java.lang.NullPointerException
The Error is because the driver under LoginPOI class is not initialized. Change your code as per below and try -
Setup Class
package BasePOI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Setup {
public static WebDriver driver;
public void Websiteopen()
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("url");
}
public Setup(WebDriver driver)
{
this.driver=driver;
}
public Setup()
{
}
public WebDriver getDriver()
{
return this.driver;
}
}
Login POI
package BasePOI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPOI
{
public WebDriver driver;
//home
By home_login=By.linkText("Login");
By about_us=By.linkText("About Us");
//login
By counselor=By.id("counselor_login");
By user=By.id("user_login");
By username=By.id("username");
By password=By.id("password");
By Login=By.name("Login");
By create_account=By.name("Login");
By Logout=By.linkText("Logout");
public void click_Login_button(){
try {
this.driver=new Setup().getDriver();
driver.findElement(home_login).click();
}
catch (Exception e)
{
System.out.println(e);
}
}
public void click_Login_counselor()
{
driver.findElement(counselor).click();
}
public void click_Login_user()
{
driver.findElement(user).click();
}
public void Enter_login_data(String uname,String pwd)
{
driver.findElement(username).clear();
driver.findElement(username).sendKeys(uname);
driver.findElement(password).clear();
driver.findElement(password).sendKeys(pwd);
}
public void click_Login()
{
driver.findElement(Login).click();
}
}
Login Class
package Functionlity;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Login
{
public WebDriver driver;
#Test
public void openwebsite() throws InterruptedException
{
Setup a= new Setup(driver);
a.Websiteopen();
LoginPOI b=new LoginPOI();
b.click_Login_button();
}
}
Explanation :
First need to make webderiver static under Setup class to make same driver accessible to different instances
create one default constructor in setup class and one method which return driver to access in another classes
this.driver=new Setup().getDriver(); will get the (initialized driver instances in setup class) driver in LoginPOI class
You are not initializing the driver object in your test class and that's why it throws null pointer exception when calling any webdriver method inside Page class.
The simple solution would be to modify your setup class and initialize the webdriver in setup method
Setup class
public class Setup {
public Webdriver getDriver() {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("url");
}
public Setup(WebDriver driver){
this.driver=driver;
}}
Test Class
public class Login {
public WebDriver driver;
#BeforeMethod
public void setup() {
driver = new FirefoxDriver();
}
#Test
public void openwebsite() throws InterruptedException{
Setup a = new Setup(driver);
a.Websiteopen();
LoginPOI b=new LoginPOI(driver);
b.click_Login_button();
}}

Null pointer exception in Java while calling the library

Now i modified the code but still i am getting Null Pointer Exception
Below is my modified code
enter code here
package lib;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeMethod;
//#SuppressWarnings("unused")
public class Login {
WebDriver driver;
#BeforeMethod
void Initalisation()
{
System.setProperty("webdriver.ie.driver", "C:\\Eclipse\\IEDriverServer.exe");
DesiredCapabilities capability=new DesiredCapabilities();
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
InternetExplorerDriver driver=new InternetExplorerDriver(capability);
driver.get("http://segotn11540.rds.volvo.com/vss_connect_testr1/Login/Login.aspx");
}
public Login(String UserName,String BrandName)
{
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
private void CheckForCancel() {
if(!driver.findElements(By.id("Cancel")).isEmpty())
{
driver.findElement(By.id("Cancel")).click();
}
}
}
Now I will create the main Java file
Blockquote
This will initalise the login with the parameters supplied
Import Login library
public class MessageBoard {
public static void main(String[] args)
{
Login login=new Login("TYP40FI","Volvo");
}
}
What is wrong in above code
Try to initialize the driver variable as
WebDriver driver = new WebDriver();
public Login(String UserName,String BrandName)
{
//Add this line in your code as you are trying in IE
driver = new InternetExplorerDriver();
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
Debug and check: Is Initalisation() being called in the beginning?
Usually #BeforeMethod is called before test starts, so where is your #Test function. (syntax could be wrong)
If you don't really care about #Test property, that means your Main function needs to call Initalisation() before calling Login(...), otherwise the driver is not set yet (aka Null)

Testing different Scenarios in “Selenium Cucumber with Java” without opening new Web browser

I have a feature file where i have 2 scenarios
Feature: Login to Online Store
Scenario: Login successful with valid credentials
Given User is on Home Page
When User navigates to Login Page
And User provides username and password
Then Message displays Login successfully
Scenario: User logout successfully
When User logouts from application
Then Message displays Logout successfully
Every time I run the RunFeatures.java file, after the first Scenario, driver to open new Browser to execute next Scenario. Can we use the same browser to execute the 2nd scenario?
Below is my code:
RunFeatures.java
package cucumbertest;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="src/test/java/features/"
,glue={"steps"}
,dryRun=false
,monochrome=false)
public class RunFeatures
{
}
ClientSteps.java:
package steps;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.*;
import pages.HomePage;
import pages.LoginPage;
public class ClientSteps
{
WebDriver driver=new FirefoxDriver();
#Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
new HomePage(driver).user_is_on_Home_Page();
}
#When("^User navigates to Login Page$")
public void user_navigates_to_Login_Page() throws Throwable {
new HomePage(driver).user_navigates_to_Login_Page();
}
#When("^User provides username and password$")
public void user_provides_username_and_password() throws Throwable {
new LoginPage(driver).user_provides_username_and_password();
}
#Then("^Message displays Login successfully$")
public void message_displays_Login_successfully() throws Throwable {
new LoginPage(driver).message_displays_Login_successfully();
}
#When("^User logouts from application$")
public void user_logouts_from_application() throws Throwable {
new LoginPage(driver).user_Logout_from_the_Application();
}
#Then("^Message displays Logout successfully$")
public void message_displays_Logout_successfully() throws Throwable {
new LoginPage(driver).message_displayed_Logout_successfully();
}
}
Homepage.java file
package pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class HomePage
{
WebDriver driver;
public HomePage(WebDriver driver)
{
this.driver=driver;
}
public void user_is_on_Home_Page() throws Throwable {
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.store.demoqa.com");
}
public void user_navigates_to_Login_Page() throws Throwable {
driver.findElement(By.xpath(".//*[#id='account']/a")).click();
}
}
LoginPage.java
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginPage
{
WebDriver driver;
public LoginPage(WebDriver driver)
{
this.driver=driver;
}
public void user_provides_username_and_password() throws Throwable {
// This is to get the first data of the set (First Row + First Column)
driver.findElement(By.id("log")).sendKeys("tri.nguyen");
// This is to get the first data of the set (First Row + Second Column)
driver.findElement(By.id("pwd")).sendKeys("Test#123");
driver.findElement(By.id("login")).click();
}
public void message_displays_Login_successfully() throws Throwable {
System.out.println("Login Successfully");
}
public void user_Logout_from_the_Application() throws Throwable {
driver.findElement (By.xpath(".//*[#id='account_logout']/a")).click();
}
public void message_displayed_Logout_successfully() throws Throwable {
System.out.println("Logout Successfully");
driver.quit();
}
}
As a good practice, test cases should be atomic. Automation Test case shouldn't be dependent on another test case for browser instance, data etc.
You rather should close all browser windows after every test case and open browser again as a new instance for a next test case.
Use #Before and #After in your stefdef file to achieve this.
as I am not able to add as a comment due to word restrictions, writing it here as a answer again! This is in continuation to my previous post. You can try this. Replace #Given by following
WebDriver driver;
#Before
public void setUp(){
driver=new FirefoxDriver();
}
#After
public void cleanUp(){
driver.quit();
}
#Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
new HomePage(driver).user_is_on_Home_Page();
}
make sure you import following files only and not junit*
import cucumber.api.java.After;
import cucumber.api.java.Before;
I tried to modify my codes following your instruction but its getting NullPointer exception:
WebDriver driver;
#Before
public void setUp(){
WebDriver driver=new FirefoxDriver();
}
#After
public void cleanUp(){
driver.quit();
}
#Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
new HomePage(driver).user_is_on_Home_Page();
}
Exception:
java.lang.NullPointerException
at pages.HomePage.user_is_on_Home_Page(HomePage.java:24)
at steps.ClientSteps.user_is_on_Home_Page(ClientSteps.java:30)
at ✽.Given User is on Home Page(Login.feature:4)
java.lang.NullPointerException
at steps.ClientSteps.cleanUp(ClientSteps.java:25)
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)
I'm again not able to add it as a comment :(.
You have declared and instantiated driver variable inside setup method which makes it local to setup method only. Declare driver at class level.
WebDriver driver;
#Before
public void setUp(){
driver=new FirefoxDriver();
}
This should work. Let me know in case you face any issues, we may get on hangout to resolve it.

can someone teach me how to use property file for a simple login application

can someone help me with using property file for a sample login application? this helps in achieving me for another big automation.
I have given objects in objects.propreties
in main java class how shall i proceed with?
package valuescompare;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class practice {
public static FileInputStream fis;
public static String propertyfilepath="E:\\Ashik\\wkspSelenium\\valuescompare\\src\\valuescompare\\object.properties";
public static String getProperty(String key) throws IOException, FileNotFoundException{
fis=new FileInputStream(propertyfilepath);
Properties prop=new Properties();
prop.load(fis);
return prop.getProperty(key);
}
static WebDriver driver=new FirefoxDriver();
public static void openBrowser() throws FileNotFoundException, IOException {
//public WebDriver driver;
driver.get(getProperty("url"));
//maximizes the window
driver.manage().window().maximize();
Wait(1000);
}
public static void login() throws FileNotFoundException, IOException{
driver.findElement(By.xpath(getProperty("uidxpath"))).sendKeys(getProperty("uid"));
driver.findElement(By.xpath(getProperty("pwdxpath"))).sendKeys(getProperty("pwd"));
driver.findElement(By.xpath(getProperty("submit"))).click();
Wait(5000);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
/*practice prac=new practice();
prac.openBrowser();
prac.login(); */
openBrowser();
login();
}
public static void Wait(int time){
try {
Thread.sleep(time);
} catch (Exception e) {
// TODO: handle exception
}
}
}
Say you create a 'config.properties' named file somewhat like this :
userName=admin
password=admin
and say you are using Java as your programming language, then you have to use it in this manner:
Properties properties = new Properties();
properties.load(new FileInputStream("Config.properties"));
String uName = properties.getProperty("userName");
String pwd = properties.getProperty("password");
Now you have got the values fetched from properties file, use it wherever required.
For more info you may refer this link: http://www.mkyong.com/java/java-properties-file-examples/

Exception in thread "main" java.lang.NullPointerException in selenium when trying to run a test case

Below is my simple testcase program:
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public WebDriver driver;
public static void main(String[] args) {
myclass dr= new myclass();
dr.start();
dr.select();
}
public void start(){
WebDriver driver= new FirefoxDriver();
driver.get("https://www.google.co.in/");
}
public void select(){
driver.findElement(By.linkText("Gmail")).click();
}
}
but it throws the below error everytime i run it:
Exception in thread "main" java.lang.NullPointerException
at mypackage.myclass.select(myclass.java:26)
at mypackage.myclass.main(myclass.java:15)
The browser gets launched and the google home page is also displayed but the next action of selecting the gmail link doesnt happen and the error appears.
**tried this on different browsers(i.e. chrome) but error still persists
please help me with this i am new to selenium..
Look up "variable scope" in Java.
This line:
driver.findElement(By.linkText("Gmail")).click();
is referencing:
public WebDriver driver;
which is never set as anything.
This should fix that error:
public void start(){
driver= new FirefoxDriver();
driver.get("https://www.google.co.in/");
}
Also, class names should start with a capital letter.
just remove the "WebDriver" instance from the start() method which is already declared above ,if you use it then "WebDriver" declare globally is not in current scope of method start()
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class myclass {
public WebDriver driver;
public static void main(String[] args) {
myclass dr= new myclass();
dr.start();
dr.select();
}
public void start(){
driver= new FirefoxDriver();
driver.get("https://www.google.co.in/");
}
public void select(){
driver.findElement(By.linkText("Gmail")).click();
}
}