This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am new to the automated tests so please, bear with me
I've been trying to execute this Selenium-generated test, but with no success. It seems that there is a problem with the Firefox Driver instantiation process. Here is a copy-paste of my Stack, followed by the test itself.
testUntitledTestCase caused an error: java.lang.NullPointerException
java.lang.NullPointerException
at SomaTeste.tearDown(SomaTeste.java:47)
It also seems that it never reaches the "driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS)". It proceeds to the "driver.quit()"(line 47) right after executing "driver = new FirefoxDriver()".
By analyzing a breakpoint placed on line 47 (which is the "driver.quit()" one), I've confirmed that the "driver" variable is set to null, which explains why i'm getting the "NullPointerException", but why is it not being initialized in the first place ? I can't seem to find an answer to this.
Does anyone have any idea on what might be causing this?
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.junit.Test;
import static org.junit.Assert.*;
public class SomaTeste{
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
baseUrl = "https://www.katalon.com/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUntitledTestCase() throws Exception {
driver.get("http://localhost:8080/SomarParcelas/");
driver.findElement(By.name("p1")).click();
driver.findElement(By.name("p1")).clear();
driver.findElement(By.name("p1")).sendKeys("21");
driver.findElement(By.name("p2")).click();
driver.findElement(By.name("p2")).clear();
driver.findElement(By.name("p2")).sendKeys("12");
driver.findElement(By.name("calcular")).click();
driver.findElement(By.xpath("//h1")).click();
assertEquals("O resultado foi 33", driver.findElement(By.xpath("//h1")).getText());
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
I cannot comment, but it works fine for me when I ran your code in Eclipse on Windows with the chrome driver. However, when I use the firefox driver, it does exactly what you are saying. It turns out to be the selenium version I used. I was using 3.3.1, but 3.9.1 works fine.
Related
Let's say I have an object:
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class SOClass {
private WebDriver driver;
private List<String> dataString;
public SOClass(WebDriver driver) throws ArrayIndexOutOfBoundsException {
this.driver = driver;
prepData();
}
private void prepData() throws ArrayIndexOutOfBoundsException {
List<WebElement> data = this.driver.findElements(By.className("a-export-table"));
if(data.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("There was no data in the table to export");
}
for(WebElement w : data) {
this.dataString.add(w.getText());
}
}
public void export(String path) throws IOException {
FileWriter fw = new FileWriter(path);
boolean isFirst = false;
for(String s : this.dataString) {
if(isFirst) {
fw.append(s);
} else {
fw.append("," + s);
}
}
fw.flush();
fw.close();
}
}
and main:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class SOMain {
private static final String COMPUTER_NAME = System.getProperty("user.name");
private static final String CHROME_PATH =
"C:/Users/" + COMPUTER_NAME + "/selenium/chromedriver.exe";
private static final String OUT_PATH = "C:/Users/" + COMPUTER_NAME + "/output/export.csv";
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", CHROME_PATH);
ChromeOptions options = new ChromeOptions();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new RemoteWebDriver(capabilities);
driver.get("www.someurlexample.com");
try {
SOClass so = new SOClass(driver);
so.export(OUT_PATH);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Now, barring any compilation issues (I made this up as an example) my code will catch any exceptions the SOClass is defined to throw. However, I was wondering if the table does not exist on the page and Selenium throws a NoSuchElementException, will my SOMain automatically catch this exception because of the
} catch(Exception e) {
}
block, or because the object is not specified to throw this error, SOMain will not handle this error and break?
Your catch will handle every exception that inherits from the Exception class (and occurs in the try obviously), which means, including NoSuchElementException as you can see here the hierarchy of it.
However, you need to distinguish Checked Exceptions and Unchecked Exceptions or Runtime Exceptions. As you can see NoSuchElementException extends java.lang.RuntimeException which means it's unchecked, therefore the compiler doesn't require you to handle it. But keep in mind that this runtime exception extends java.lang.Exception so your catch will catch it during runtime if it occurs.
I am learning selenium and Java.
Trying to create a test script to book hotel, then view the itinerary and finally perform logout operation on a test site.
After clicking "book_now" button it takes some time to load the next frame/page where the itinerary button exists.
I explicitly added "waitForFrameToLoad" command as the test case was failing on IDE stating "my_Itinerary" element not found.
After addition test case passed on IDE and when exported using junit/webdriver option,I see the below note:
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class CompleteBooking {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.adactin.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testCompleteBooking() throws Exception {
driver.get(baseUrl + "/HotelAppBuild2/");
driver.findElement(By.id("username")).sendKeys("pranu86”);
driver.findElement(By.id("password")).sendKeys("test”);
driver.findElement(By.id("login")).click();
new Select(driver.findElement(By.id("hotels"))).selectByVisibleText("Hotel Sunshine");
driver.findElement(By.id("Submit")).click();
driver.findElement(By.id("radiobutton_0")).click();
driver.findElement(By.id("continue")).click();
driver.findElement(By.id("first_name")).sendKeys("pranu");
driver.findElement(By.id("cc_num")).sendKeys("1234567891234567");
new Select(driver.findElement(By.id("cc_type"))).selectByVisibleText("VISA");
driver.findElement(By.id("book_now")).click();
// ERROR: Caught exception [ERROR: Unsupported command [waitForFrameToLoad | http://www.adactin.com/HotelAppBuild2/BookingConfirm.php | 10000]]
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
driver.findElement(By.id("my_itinerary")).click();
// ERROR: Caught exception [unknown command [clickAndWait ]]
driver.findElement(By.linkText("Click here to login again")).click();}
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);}}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;}}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;}}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
How to fix this issue/Error note? Please help
I created a class which has page objects defined in it. Then I am trying to use that class in a test class by using a constructor. However when I run the test class using JUnit I am getting a NullPointerException error.
Page_Objects Class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;
public class Page_Objects {
private WebDriver driver;
WebElement Username = driver.findElement(By.id("username"));
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
WebElement Password = driver.findElement(By.id("password"));
WebElement Login_Button = driver.findElement(By.id("Login"));
WebElement Logout_Button = driver.findElement(By.linkText("Logout"));
}
Test Class:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Salesforce_Test {
private WebDriver driver1;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
Page_Objects pageobjects = new Page_Objects();
#Before
public void setUp() throws Exception {
driver1 = new FirefoxDriver();
baseUrl = "some url for testing/";
driver1.navigate().to(baseUrl);
driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void Login_Logout() throws Exception {
pageobjects.Username.sendKeys("someusername");
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
pageobjects.Password.sendKeys("somepassword");
pageobjects.Login_Button.click();
pageobjects.Logout_Button.click();
}
#After
public void tearDown() throws Exception {
driver1.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver1.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver1.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver1.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
When I run the above class I get a null pointer exception.
java.lang.NullPointerException
at Page_Objects.<init>(Page_Objects.java:20)
at Salesforce_Test.<init>(Salesforce_Test.java:16)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
I see two issues here. First is that the Page_Objects class is called before you initiated the driver. That's why when you're calling
Page_Objects pageobjects = new Page_Objects();
you're getting a NullPointerException.
So you want to initiate the Page_Objects after you've initiated the driver.
Second, you need to pass it the instance of the driver you've initiated, because right now it has its own Private driver which isn't initiated and therefore it's null.
So in short:
Initiate Page_Objects after you've initiated driver (after the driver1 = new FirefoxDriver(); line)
Call it with the driver you've initiated: Page_Objects pageobjects = new Page_Objects(driver1 );
I am running my script and it terminates after 4 seconds. Have been stuck on this for hours, any help very much appreciated. Could it be that I may be using JUnit 3 code somewhere in a Junit 4 script? Just a thought. I am also calling a seperate PageObjects script, could this be the reason? Code is below:
package com.testcases;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import jxl.*;
import com.PageObjects.RegisterUserPageObject;
import java.io.File;
import jxl.write.*;
public class RegisterUser {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://newtours.demoaut.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testRegisterUser() throws Exception {
RegisterUserPageObject registerUserPage = PageFactory.initElements (driver, RegisterUserPageObject.class);
Workbook wb = Workbook.getWorkbook(new File("C:\\Users\\mce\\Documents\\Selenium\\Projects\\Mecury Tours\\Data1.xls"));
WritableWorkbook copy = Workbook.createWorkbook(new File("C:\\Users\\mce\\Documents\\Selenium\\Projects\\Mecury Tours\\Data2.xls"),wb);
WritableSheet s = copy.getSheet(0);
for(int i=1;i<s.getRows();i++)
{
driver.get(baseUrl + "/");
driver.findElement(By.xpath("//a[contains(text(),'Register \n here')]")).click();
driver.findElement(By.name("firstName")).sendKeys("Tester");
driver.findElement(By.name("lastName")).clear();
driver.findElement(By.name("lastName")).sendKeys("01");
driver.findElement(By.name("phone")).clear();
driver.findElement(By.name("phone")).sendKeys("010101010");
driver.findElement(By.id("userName")).clear();
driver.findElement(By.id("userName")).sendKeys("test#test.com");
driver.findElement(By.name("address1")).clear();
driver.findElement(By.name("address1")).sendKeys("1 Test Ave");
driver.findElement(By.name("city")).clear();
driver.findElement(By.name("city")).sendKeys("Dublin");
driver.findElement(By.name("state")).clear();
driver.findElement(By.name("state")).sendKeys("Leinster");
new Select(driver.findElement(By.name("country"))).selectByVisibleText("IRELAND");
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(s.getWritableCell("A"+i).getContents());
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("password");
driver.findElement(By.name("confirmPassword")).clear();
driver.findElement(By.name("confirmPassword")).sendKeys("password");
driver.findElement(By.name("register")).click();
driver.findElement(By.linkText("Home")).click();
s.addCell(new Label(4,i,"Executed"));
}
copy.write();
copy.close();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
How to use this code :
public boolean isElementPresent(By by)
When I export my test script there will be automatically in the test script, but most of the method below is not used, so there will warnings stated that I'm not using that method..and my test script will be failed.
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class cheesecake {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.google.com.my/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testCheesecake() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("cheesecake");
driver.findElement(By.cssSelector("a.q.qs")).click();
driver.findElement(By.cssSelector("span.mn-dwn-arw")).click();
driver.findElement(By.xpath("//a[contains(text(),'News')]")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
Can I know what is the use of all these methods and how to use it? Because, if I deleted them, my test script can run but even though I put a wrong password also can log in to the system.
You are right, this is auto generated by the IDE but you have incorrectly edited it:
public boolean isElementPresent(By by) {
try {
driver.findElements(by);
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}
Then call it with:
isElementPresent(By.id("J_idt16:J_idt30"));
It is there to make it easier to determine whether an element is visible on the page. Sometimes you want to have that element and do something with it, other times you just want to know if it's present or not. This is there to make it easy to do so.
If you are having problems with your test script, please post the code you are using and the HTML you are running against or try and reproduce it with a different public facing website.