java.lang.NullPointerException error - Intellij IDEA, Selenium, Java [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am in the process of automating a set of manual tests on a website.
As the website is still in the process of being developed and tested, it is constantly under change. Therefore, my idea is to create a standard set of 'master' tests that are used in most (if not all) tests, that I can call from other tests and that can be easily changed where necessary.
I have created a package called 'Master', containing two classes called 'Login' and 'Logout'. I have created another package called 'SmokeTests', containing a class called 'Smoke003'.
The Login script runs successfully when I call it from Smoke003 however, I cannot seem to write/run the Logout script successfully.
Please see below my code for the 3 different classes:
Login:
package Master;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static junit.framework.TestCase.assertEquals;
public class Login {
static WebDriver driver;
#Test
public void testLogin(){
String loginname1 = "EMAIL HERE";
String password1 = "PASSWORD HERE";
driver = new FirefoxDriver();
driver.get("WEBSITE HERE");
driver.findElement(By.id("LoginButton")).click();
driver.findElement(By.id("loginEmail")).sendKeys(loginname1);
driver.findElement(By.id("loginPassword")).sendKeys(password1);
driver.findElement(By.id("loginOKButton")).click();
new WebDriverWait(driver,5).until(ExpectedConditions.textToBePresentInElementLocated(By.className("underline"),"Events"));
assertEquals("TEXT HERE",driver.findElement(By.className("TEXT HERE")).getText(),"TEXT HERE");
}
}
Logout:
package Master;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Logout {
static WebDriver driver;
#Test
public void testLogout(){
driver.findElement(By.cssSelector("TEXT HERE")).click();
}
}
SMOKE003:
package SmokeTests;
import Master.Login;
import Master.Logout;
import org.junit.Test;
public class Smoke_003 {
public static void main(String args[]) {
Login Login01 = new Login();
Login01.testLogin();
Logout Logout01 = new Logout();
Logout01.testLogout();
}
Is anybody please able to help with why I keep receiving the error message 'java.lang.NullPointerException' when running/debugging the logout test? I am aware that there is no driver.get website specified in the Logout script. I don't believe I need to do this as by the time I come to logout I will already be logged in?
NOTE: I have edited some information such as email address etc. for confidentiality reasons.
UPDATE: If I run Smoke003, it calls the login script and logs in successfully but fails when trying to call the logout script with the following error message in full:
Exception in thread "main" java.lang.NullPointerException
at Master.Logout.testLogout(Logout.java:14)
at SmokeTests.Smoke_003.main(Smoke_003.java:14)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

You forgot to instanciate the driver. Try the following:
public class Logout {
static WebDriver driver;
#Test
public void testLogout(){
driver = new FirefoxDriver();
driver.get("WEBSITE HERE");
driver.findElement(By.cssSelector("TEXT HERE")).click();
}

You should add an #Before method to instantiate the driver. A method annotated with #Before will run before every test
#Before
public void setup(){
driver = new FirefoxDriver();
}

Related

Cucumber Java program does not pick up step definition

I'm new with cucumber and learned this doc carefully to understand how could I implement my first cucumber java project. I have done a lot of analysis and gone through almost all the articles related to it over internet, why its not picking up step definition but could not find the cause. However, everything seems to be OK as per my understanding, I have great expectation that you guys can find my fault at one go.
Looking forward for a +ve response.
Hence I'm sharing the code, message(on console window) and folder structure.
Thanks
Rafi
Feature file:
#MyApplication
Feature: Post text Hello Rafi on Rafi facebook account
Scenario: Login successfully on Facebook application
Given Open Facebook application
When Enter valid id and password
And Click on Login button
Then Facebook home page should open
TestRunner class:
package test.java.runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
//glue = {"helpers", "src.test.java.steps"},
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/features"},
glue = {"helpers", "src.test.java.steps"},
plugin = {"pretty","html:target/cucumber-html-report"},
dryRun = true,
monochrome = true,
tags="#MyApplication",
strict=false)
public class TestRunner {
}
StepDefinition class:
package test.java.steps;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinition {
private static WebDriver driver = null ;
private static String password = "*********";
WebDriverWait wait=new WebDriverWait(driver, 30);
WebElement waitElement;
#BeforeClass
public void setup() throws Throwable
{
System.setProperty("webdriver.gecko.driver", "C:\\Selenium Automation\\selenium\\Selenium 3 and Firefox Geckodriver\\geckodriver.exe");
driver = new FirefoxDriver ();
driver.manage().window().maximize();
}
#AfterClass
public void teardown() throws Throwable
{driver.quit();}
// First scenario
#Given("^Open Facebook application$")
public void open_Facebook_application() throws Throwable{
System.out.println("this is not working");
driver.navigate().to("https://www.facebook.com/");
}
#When("^Enter valid id and password$")
public void enter_valid_id_and_password() throws Throwable{
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys("rafiras16#gmail.com");
driver.findElement(By.name("pass")).clear();
driver.findElement(By.name("pass")).sendKeys(password);
}
#When("^Click on Login button$")
public void click_on_Login_button() throws Throwable {
driver.findElement(By.xpath("//input[starts-with(#id,'u_0')]")).click();
}
#Then("^Facebook home page should open$")
public void facebook_home_page_should_open() throws Throwable{
String strTitle = driver.getTitle();
System.out.print(strTitle);
}
}
image for message on console window and folder structure
BuildPath details
I think the glue attribute on the CucumberOptions class is wrong. If you want to refer to the step definitions using the file path then you need to change that to:
glue = {"helpers", "src/test/java/steps"},
If you want to refer them by package then you need to remove the "src." prefix:
glue = {"helpers", "test.java.steps"},
Try changing,
glue = {"helpers", "src.test.java.steps"}
to
glue = {"test.java.steps"}
And what is this helpers package i don't see it in the screenshot.
The #AfterClass and #BeforeClass annotations are useful only if the class is a junit test class. You have placed them in a normal class, thus they will not be run. This leads to the driver remaining uninitaialized.
The easy way out is to use the cucumber #Before and #After annotation. Change the #BeforeClass to #Before and #AfterClass to #After.

automatic login to gmail error occuring through firefox

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Login {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("https://www.mail.google.com");
driver.findElement(By.id("Email")).sendKeys("abc#gmail.com");
driver.findElement(By.id("Passwd")).sendKeys("xyz");
driver.findElement(By.id("signIn")).click();
}
}
I am trying to write a program to login automatically into gmail.
I have tried everything
please help!!!!
This is giving me the error like this:
Exception in thread "main" java.lang.NoSuchMethodError:com.google.common.
base.Platform.precomputeCharMatcher
(Lcom/google/common/base/CharMatcher;)
Lcom/google/common/base/CharMatcher;
at com.google.common.base.CharMatcher.precomputed(CharMatcher.java:664)
at com.google.common.base.CharMatcher.(CharMatcher.java:71)
at com.google.common.base.Splitter.on(Splitter.java:127)
at org.openqa.selenium.remote.http.JsonHttpCommandCodec.
(JsonHttpCommandCodec.java:59)
at org.openqa.selenium.remote.HttpCommandExecutor.
(HttpCommandExecutor.java:85)
at org.openqa.selenium.remote.HttpCommandExecutor.
(HttpCommandExecutor.java:70)
at org.openqa.selenium.remote.HttpCommandExecutor.
(HttpCommandExecutor.java:58)
at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.
start(NewProfileExtensionConnection.java:87)
at org.openqa.selenium.firefox.FirefoxDriver.startClient
(FirefoxDriver.java:271)
at org.openqa.selenium.remote.RemoteWebDriver.
(RemoteWebDriver.java:119)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:218)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:211)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:207)
at org.openqa.selenium.firefox.FirefoxDriver.
(FirefoxDriver.java:120)
at com.st.Login.main(Login.java:17)
First of all: that URL doesn't go anywhere (at least in my side). You can achieve what you want as follows:
driver.get("https://accounts.google.com/")
driver.findElement(By.id("Email")).sendKeys("");
driver.findElement(By.id("next")).click();
driver.findElement(By.id("Passwd")).sendKeys("");
driver.findElement(By.id("signIn")).click();

How to create two object drivers of type WebDriver and use the same Classes and Methods

I have a question related to improving my Selenium Java code. I am really beginner in Java and Selenium either.
I have written a code which I got an example from the internet and adapted to my reality. The coding works fine as described below:
package test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import page.Login;
public class LoginTest extends BaseTest {
Login login = new Login(driver);
#Test
public void loginWithSuccess() {
sendLoginData("my_user#something.com", "my_password");
login.clickLogin();
assertEquals("View Posted Jobs", login.checkLoginSuccess());
}
private void sendLoginData(String user, String password) {
login.sendUser(user);
login.sendPassword(password);
}
}
The above program is testing and performing a loginWithSucess in the WebSite
package config;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebDriverFactory {
public static WebDriver createFirefoxDriver() {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
In this above example I am instancing a new object WebDriver called driver.
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import config.WebDriverFactory;
public class BaseTest {
protected static WebDriver driver;
private static boolean setUpIsDone = false;
#BeforeClass
public static void setUp() {
if (setUpIsDone) {
return;
}
// Creating first browser for student login
driver = WebDriverFactory.createFirefoxDriver();
driver.get("http://test-tuitiondesk.rhcloud.com/auth");
driver.manage().window().maximize();
setUpIsDone = true;
}
The above example is where I open my WebSite to authenticate
package page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Login {
private WebDriver driver;
public Login(WebDriver driver) {
this.driver = driver;
}
public void sendUser(String user) {
driver.findElement(By.xpath("//*[#id='email']")).sendKeys(user);
}
public void sendPassword(String password) {
driver.findElement(By.id("password")).sendKeys(password);
}
public void clickLogin() {
driver.findElement(By.xpath("//*[#id='login-box']/div/div[1]/form/fieldset/div[2]/button")).click();
}
public String checkLoginSuccess() {
return driver.findElement(By.xpath("//a[contains(text(),'View Posted Jobs')]")).getText();
}
}
The above example I have methods which will send a user id and password to the webpage.
So far is everything working fine. The program is performing the following steps:
1 - Open the firefox
2 - Open the webpage
3 - Send the correct user_id, password and click in login button
4 - Check if login was performed with success.
My question now is that I need open a new firefox driver and login with different user_id and this new user_id will interact some actions with the first user_id, so I will need two browsers opened to perform actions with both users in the same time.
I would like to write this implementation the best way than simply write every method again with the second driver. What I thought for the first time was create a new WebDriver called driver2 and create again all methods referring to driver2, but I think I should reuse my methods and classes in a clever way.
Does Anybody have any idea how to implement this second browser in my code?
Thank you
André
You can do this simply by entering this code:
driver2 = WebDriverFactory.createFirefoxDriver();
driver2.get("http://test-tuitiondesk.rhcloud.com/auth");
//call log in function for driver2
//code to interact driver2 with driver1

Maintain and re-use existing webdriver browser instance - java

Basically every time I run my java code from eclipse, webdriver launches a new ie browser and executes my tests successfully for the most part. However, I have a lot of tests to run, and it's a pain that webdriver starts up a new browser session every time. I need a way to re-use a previously opened browser; so webdriver would open ie the first time, then the second time, i run my eclipse program, I want it to simply pick up the previous browser instance and continue to run my tests on that same instance. That way, I am NOT starting up a new browser session every time I run my program.
Say you have 100 tests to run in eclipse, you hit that run button and they all run, then at about the 87th test you get an error. You then go back to eclipse, fix that error, but then you have to re-run all 100 test again from scratch.
It would be nice to fix the error on that 87th test and then resume the execution from that 87th test as opposed to re-executing all tests from scratch, i.e from test 0 all the way to 100.
Hopefully, I am clear enough to get some help from you guys, thanks btw.
Here's my attempt below at trying to maintain and re-use a webdriver internet explorer browser instance:
public class demo extends RemoteWebDriver {
public static WebDriver driver;
public Selenium selenium;
public WebDriverWait wait;
public String propertyFile;
String getSessionId;
public demo() { // constructor
DesiredCapabilities ieCapabilities = DesiredCapabilities
.internetExplorer();
ieCapabilities
.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
driver = new InternetExplorerDriver(ieCapabilities);
this.saveSessionIdToSomeStorage(getSessionId);
this.startSession(ieCapabilities);
driver.manage().window().maximize();
}
#Override
protected void startSession(Capabilities desiredCapabilities) {
String sid = getPreviousSessionIdFromSomeStorage();
if (sid != null) {
setSessionId(sid);
try {
getCurrentUrl();
} catch (WebDriverException e) {
// session is not valid
sid = null;
}
}
if (sid == null) {
super.startSession(desiredCapabilities);
saveSessionIdToSomeStorage(getSessionId().toString());
}
}
private void saveSessionIdToSomeStorage(String session) {
session=((RemoteWebDriver) driver).getSessionId().toString();
}
private String getPreviousSessionIdFromSomeStorage() {
return getSessionId;
}
}
My hope here was that by overriding the startSession() method from remoteWebdriver, it would somehow check that I already had an instance of webdriver browser opened in i.e and it would instead use that instance as opposed to re-creating a new instance everytime I hit that "run" button in eclipse.
I can also see that because I am creating a "new driver instance" from my constructor, since constructor always execute first, it creates that new driver instance automatically, so I might need to alter that somehow, but don't know how.
I am a newbie on both stackoverflow and with selenium webdriver and hope someone here can help.
Thanks!
To answer your question:
No. You can't use a browser that is currently running on your computer. You can use the same browser for the different tests, however, as long as it is on the same execution.
However, it sounds like your real problem is running 100 tests over and over again. I would recommend using a testing framework (like TestNG or JUnit). With these, you can specify which tests you want to run (TestNG will generate an XML file of all of the tests that fail, so when you run it, it will only execute the failed tests).
Actually you can re-use the same session again..
In node client you can use following code to attach to existing selenium session
var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
// The 'capabilities' object as returned by sessionCapabilities
if (err) { /* that session doesn't exist */ }
else {
browser.elementByCss("button.groovy-button", function(err, el) {
...
});
}
});
...
browser.detach();
To get selenium session id,
driver.getSessionId();
Note:
This is available in Node Client only..
To do the same thing in JAVA or C#, you have to override execute method of selenium to capture the sessionId and save it in local file and read it again to attach with existing selenium session
I have tried the below steps to use the same browser instance and it worked for me:
If you are having generic or Class 1 in different package the below code snippet will work -
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
// Class 1 :
public class Generics {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "url";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
// Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
#Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
driver.findElement(By.cssSelector("")).sendKeys("");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
driver.findElement(By.xpath("")).sendKeys("");
}
}
If your Generics class is in the same package you just need to make below change in your code:
public class Generics {
public Generics(){}
WebDriver driver; }
Just remove the protected word from Webdriver code line. Rest code of class 1 remain as it is.
Regards,
Mohit Baluja
I have tried it by extension of classes(Java Inheritance) and creating an xml file. I hope below examples will help:
Class 1 :
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
public class SetUp {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "URL";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import zgenerics.SetUp
public class Conditions extends SetUp {
#Test
public void visible() throws InterruptedException{
Thread.sleep(5000);
boolean signINbutton=driver.findElement(By.xpath("xpath")).isEnabled();
System.out.println(signINbutton);
boolean SIGNTEXT=driver.findElement(By.xpath("xpath")).isDisplayed();
System.out.println(SIGNTEXT);
if (signINbutton==true && SIGNTEXT==true){
System.out.println("Text and button is present");
}
else{
System.out.println("Nothing is visible");
}
}
}
Class 3:
package automationScripts;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
public class Footer extends Conditions {
#Test
public void footerNew () throws InterruptedException{
WebElement aboutUs = driver.findElement(By.cssSelector("CssSelector"));
aboutUs.click();
WebElement cancel = driver.findElement(By.xpath("xpath"));
cancel.click();
Thread.sleep(1000);
WebElement TermsNCond = driver.findElement(By.xpath("xpath"));
TermsNCond.click();
}
}
Now Create an xml file with below code for example and run the testng.xml as testng suite:
copy and paste below code and edit it accordingly.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="classes" thread-count="3">
<test name="PackTest">
<classes>
<class name="automationScripts.Footer"/>
</classes>
This will run above three classes. That means one browser and different tests.
We can set the execution sequence by setting the class names in alphabetical order as i have done in above classes.

Jenkins Build is not stopped after successfully passing the Integration test

Hi I am new to Jenkins.
I have configure the Jenkins locally on my machine and Its running fine.
I need to ask whenever my Integration tests (written in Junit) are passed, Jenkin doesn't stops the build and its continue.
But in logs It displays the test cases are passed and no errors are found.
Could some one please suggest any solution how to stop jenkins build?
My Code:
package com.workshop.airport.workshop.airport;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import cucumber.api.java.After;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class PageStepsDefs {
public String ChromeDriverPath="C:\\Users\\zain.jamshaid\\Desktop\\chromedriver.exe";
public WebDriver webdriver;
String localhost="http://www.google.com";
public PageStepsDefs (){
System.setProperty("webdriver.chrome.driver",ChromeDriverPath);
webdriver = new ChromeDriver();
}
#Given("^I browse to the (.+) page$")
public void open_page(String url)
{
webdriver.get(localhost+url);
System.out.println(localhost+url);
}
#When("^I click on the button (.+)$")
public void click_On_Menu(String Id)
{
webdriver.findElement(By.id(Id)).click();
System.out.print(Id);
}
#After
public void close_browser(){
webdriver.close();
}
}
I have also attached the screenshot of jenkins console logs
Any help will be awesome.
Thanks!
I was using webDriver.close();
but
webDriver.quit();
fix my problem
This fixed the problem

Categories

Resources