java.lang.NullPointerException at feature.StepDefinitions cucumber - selenium

I'm getting a NullPointerException as follows:
Feature: Login action
Scenario:
Successful Login with Valid Credentials # C:/Users/chaitanya/workspace/cucumber2/src/feature/myfeature.feature:3
Given User is on Home Page # StepDefinitions.User_is_on_Home_Page()
When User enters UserName and Password # StepDefinitions.User_enters_UserName_and_Password()
java.lang.NullPointerException
at feature.StepDefinitions.User_enters_UserName_and_Password(StepDefinitions.java:25)
at ?.When User enters UserName and Password(C:/Users/chaitanya/workspace/cucumber2/src/feature/myfeature.feature:5)
Then Message displayed Login Successfully # StepDefinitions.Message_displayed_Login_Successfully()
Code:
package feature;
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.Then;
import cucumber.api.java.en.When;
public class StepDefinitions {
public static WebDriver driver;
#Given("^User is on Home Page$")
public void User_is_on_Home_Page() throws Throwable {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://opensource.demo.orangehrmlive.com/");
}
#When("^User enters UserName and Password$")
public void User_enters_UserName_and_Password() throws Throwable {
driver.findElement(By.name("txtUsername")).sendKeys("admin");
driver.findElement(By.xpath("//input[#id='txtPassword']")).sendKeys("admin");
driver.findElement(By.name("Submit")).click();
Thread.sleep(3000);
}
#Then("^Message displayed Login Successfully$")
public void Message_displayed_Login_Successfully() throws Throwable {
System.out.println("login completed");
}
}

In User_is_on_Home_Page() you're using a local variable named driver within that method. You're not setting the static driver that your other methods are using. As a result, when they reference driver it is still null.
The solution is to change:
public static WebDriver driver;
to:
public static final WebDriver driver = new FirefoxDriver();
and remove the WebDriver driver = new FirefoxDriver(); line from User_is_on_Home_Page() so that it likewise refers to the static instance.
Alternatively, instantiate the static driver instance lazily. Replace:
WebDriver driver = new FirefoxDriver();
in User_is_on_Home_Page() with:
if (driver == null) {
driver = new FirefoxDriver();
}

Related

Getting InvalidArgumentException

package trails2110;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo01 {
WebDriver driver;
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Eclipse\\Drivers\\chromedriver.exe");
System.out.println("1");
driver= new ChromeDriver();
System.out.println("2");
}
#After
public void tearDown() throws Exception {
driver.close();
}
#Test
public void test() {
String url= "www.hotstar.com";
System.out.println("3");
driver.get(url);
System.out.println("4");
String Title=driver.getTitle();
System.out.println(Title);
}
}
In Console till 3 its getting printed.
I have latest version of chrome and latest version of chrome driver for it.
i tried with multiple drivers didnt work.
am i missing something?
I am able to route to the url with the following code
System.setProperty("webdriver.chrome.driver", "D:\\Eclipse\\Drivers\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
String url = "https://www.google.com";
String script = "window.location = \'"+url+"\'";
((JavascriptExecutor) driver).executeScript(script);
any reasons its not happening with get() method and happening with JavascriptExecutor ?
You should declare the URL with its protocol. So
String url= "www.hotstar.com";
url = "https://" + url

I'm not getting title of the page,i tried in firefox as well as in chrome

I'm not getting title of the page,i tried in firefox as well as in chrome.
This is my package
package begin;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Title {
WebDriver driver;
public void tite()
{
driver=new FirefoxDriver();
System.setProperty("webdriver.firefox.driver","C:/selenium-java-3.0.0-beta3/Latest selenium/geckodriver.exe");
driver.get("http://newtours.demoaut.com/");
String titleofthepage=driver.getTitle();
System.out.println(titleofthepage);
}
public static void main(String[] args)
{
Title obj1=new Title();
obj1.tite();
}
}
Need to add wait attributes to driver element.
After creating driver add implicit wait
System.setProperty("webdriver.firefox.driver","geckodriverpath");
driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
You are finding page title immediately after launching web page. Here it will wait 30 secs before finding any element to web page.
Set the property before driver initialization So your code should be :
package begin;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Title {
WebDriver driver;
public void tite()
{
System.setProperty("webdriver.firefox.driver","C:/selenium-java-3.0.0-beta3/Latest selenium/geckodriver.exe");
driver=new FirefoxDriver();
driver.get("http://newtours.demoaut.com/");
String titleofthepage=driver.getTitle();
System.out.println(titleofthepage);
}
public static void main(String[] args)
{
Title obj1=new Title();
obj1.tite();
}
}

Launching URL using Selenium gecko driver

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CheckoutFlow {
public static void main(String[] args) {
// TODO Auto-generated method s
System.setProperty("webdriver.gecko.driver", "D:\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
driver.get("http://google.com");
}
}
While launching the URL - from Java code below error is coming
"Server not Found"
Your code is perfectly fine. This might be the issue with Firefox version,
firefox version(I'm using) 52.0.1.
If still it is not working then try to switch to chrome instead of firefox.
Chrome Code :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CheckoutFlow {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://google.com");
driver.manage().window().maximize();
driver.quit();
}
}

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.