This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Have below Selenium Program using Object Repository Library File but the same is failing and shows java.lang.NullPointerException. Have commented the specific syntax lines as "error". Also attached the error screenshot and config.property files.enter image description here. Have tried to identify the cause but could not. please clarify the cause of the failing and error message.
package objectrepository;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import objectrepository.Lib_ChromeDriver;
public class OBRClass_2 {
#Test
public void launch_chrome() throws Exception{
Lib_ChromeDriver LCD = new Lib_ChromeDriver();// Lib_ChromeDriver is the Object Repository Library File
System.setProperty("webdriver.chrome.driver", LCD.Path());// error shown
WebDriver Snap = new ChromeDriver();
Snap.get(LCD.AppURL());
}
}
and:
// a Java Class containing Constructor & method and is saved as Library file.
// Constructor has will call the ObjectRepository File and
// method will call the Call the ChromeDriver Location to Launch the same
// this Library Class can be called in Selenium program to launch the Chrome Driver
package objectrepository;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.testng.annotations.Test;
public class Lib_ChromeDriver {
Properties Prop;
#Test
public void Lib_ChromeDriver() throws Exception{// Constructor calling the Object Repository File
File OB_File = new File("./Config/Config.property");
FileInputStream OB_FIS = new FileInputStream(OB_File);
Prop = new Properties();
Prop.load(OB_FIS);
}
public String Path() throws Exception{// method calling the ChromeDriver Path to Launch the same
String ChromePath = Prop.getProperty("ChromeDriver"); // error shown
return ChromePath;
}
public String AppURL() throws Exception{
String AppURL = Prop.getProperty("URL");
return AppURL;
}
}
change
public void Lib_ChromeDriver() // not a constructor
to
public Lib_ChromeDriver() // is a constructor
the code you are calling is not in your constructor but in a method called Lib_ChromeDriver
In this case your code is calling the default constructor which does not have any code in it - therefore the variable Props is never set
Related
This question already has answers here:
Java: NullPointerException from class.getResource( ... )
(5 answers)
InputStream.getResourceAsStream() giving null pointer exception
(7 answers)
Closed 1 year ago.
I am relatively new to Java, and as a learning experience, tried to build a classifier in java by reading a dataset from a file called "dataset.csv"
This is the code I wrote for the whole class:
import java.io.IOException;
import weka.classifiers.trees.J48;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.core.converters.CSVLoader;
import weka.core.Instances;
public class classifier {
public static final String DATASET = "dataset.csv";
public static Instances getData(String filename) throws IOException
{
CSVLoader loader = new CSVLoader();
loader.setSource(classifier.class.getResourceAsStream("/"+filename));
System.out.println("getData function running");
Instances dataset = loader.getDataSet();
return dataset;
}
public static void J48Classifier() throws Exception
{
Instances dataset = getData(DATASET);
Classifier j48 = new J48();
j48.buildClassifier(dataset);
Evaluation eval = new Evaluation(dataset);
eval.evaluateModel(j48,dataset);
System.out.println("Evaluation with dataset: ");
System.out.println(eval.toSummaryString());
System.out.println("Expression as per the algorithm: ");
System.out.println(j48);
System.out.println(eval.toMatrixString());
System.out.println(eval.toClassDetailsString());
}
public static void main(String args[]) throws Exception
{
J48Classifier();
}
}
But once I run the code, I am getting this error:
This is my file Structure for reference (the dataset.csv file is located in the src directory of the below cited image):
Can anyone help me figure out if I have missed out on something?
I am getting the error to access the data from the properties file in my selenium UI : How can this be solved ?
org.openqa.selenium.WebDriverException: unknown error: keys should be a string.
I have the following framework. I made it for my self for ease, looks like complicating myself. If any good ideas to better it, please suggest.
Appreciate all suggestions.
Framework contains the following :
1. config properties file
2. utilities class
3. Page elements definition class file
4. reusable functions class file
5. test classes
config.properties file has the following content :
url=http://some.com
Email=someuser
Password=somepassword
Utilities class (BrowserCalls) the following code :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class BrowserCalls {
public WebDriver driver;
public Properties configs = new Properties();
public String pathToProperties = "path to config.properties file";
public void invokeChromeBrowser() throws IOException {
FileInputStream input = new FileInputStream(pathToProperties);
pmsConfigs.load(input);
System.setProperty("webdriver.chrome.driver", configs.getProperty("chromepath"));
driver = new ChromeDriver();
getAndMazimize();
}
private void getAndMazimize(){
driver.get(configs.getProperty("url"));
driver.manage().window().maximize();
}
public void closeChromeBrowser(){
if(driver != null){
driver.close();
}
}
}
Page elements definition class file has the following code :
import org.openqa.selenium.By;
public class LoginPageElements {
//Login page elements
public static By element1 = By.xpath("/html/head/link[1]");
public static By username = By.xpath("//*[#id=\"login\"]/input/tr1/td1");
public static By password = By.xpath("//*[#id=\"login\"]/input/tr2/td1");
public static By submitButton = By.xpath("//*[#id=\"login\"]/input/tr3/td2/button");
public static By title = By.xpath("/html/head/title");
}
Functionality definition classes to be called by test case classes :
import com.automation.PageElements.LoginPageElements;
import com.automation.ReusableFunctions.BrowserCalls;
public class LoginFeature extends BrowserCalls {
public void userLogin(){
driver.findElement(LoginPageElements.element1);
driver.findElement(LoginPageElements.username).sendKeys(configs.getProperty(Email));
driver.findElement(LoginPageElements.password).sendKeys(configs.getProperty(Password));
driver.findElement(LoginPageElements.submitButton).click();
}
}
Test Case class is as below :
import com.automation.ReusableFunctions.BrowserCalls;
import com.automation.Components.LoginFeature;
import org.testng.annotations.Test;
import java.io.IOException;
public class LoginTestCase1 extends BrowserCalls {
#Test (description = "Verify application login")
public void LoginTest() throws IOException {
LoginFeature login = new LoginFeature();
login.invokeChromeBrowser();
login.userLogin();
login.closeChromeBrowser();
}
}
You can check what this two statements return like this:
System.out.println(System.getProperty("Email"));
System.out.println(System.getProperty("Password"));
probably they are returning null, and that's why you are getting error.
Try this:
public void userLogin(){
System.out.println(System.getProperty("Email")); // check statement return
System.out.println(System.getProperty("Password")); // check statement return
driver.findElement(LoginPageElements.element1);
driver.findElement(LoginPageElements.username).sendKeys(configs.getProperty("Email"));
driver.findElement(LoginPageElements.password).sendKeys(configs.getProperty("Password"));
driver.findElement(LoginPageElements.submitButton).click();
}
PS
System.getProperty("key") // should be like this
System.getProperty(key) // not like this
Change these two lines to :
driver.findElement(LoginPageElements.username).sendKeys(configs.getProperty(Email))
driver.findElement(LoginPageElements.password).sendKeys(configs.getProperty(Password));
To:
driver.findElement(LoginPageElements.username).sendKeys(configs.getProperty("username"))
driver.findElement(LoginPageElements.password).sendKeys(configs.getProperty("password"));
Now talking about the suggestion part :
There is some serious issue in this class : LoginPageElements , and that is because of absolute xpath.
For example : You are using this xpath : //*[#id=\"login\"]/input/tr3/td2/button to click on submit button.
A good alternative would suggest you to use relative xpath something like :
//button[text()='Submit'] // This may not work cause you have not shared the HTML for the submit button. Here I am just guessing.
different alternative would be to go with : sendKeys(Keys.RETURN) , if and only if the application support clicking on enter after providing the username and password.Something like this in code :
driver.findElement(LoginPageElements.password).sendKeys(configs.getProperty("password"+Keys.RETURN));
Though as suggested by #Andrei , if you are heavily dependent on login as test method , then you should write a relative xpath or any other locator for the submit button instead of Keys.RETURN.
Your all xpath are absolute , try to write locators as in this order :
id
classname
linkText
partialLinkText
tagName
css selector
xpath (Try to be more relative than absolute)
Some time ago I was have troubles with property file, the problem was with line separators, when I opened property file with Notepad++ all looked fine, but line separators was missing when file was opened with Notepad. Possibly it will help
Don't save the Excel table with Excel icon in Excel sheet.
Save the Excel sheet with the button in Eclipse.
Please check the Image Link given below:-
enter image description here
The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()
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();
}
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.