Exception Selenium Webdriver TestNg [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Tried to create properties file and retrieving information from it , but am getting an java.lang.NullPointerException ,also tried try and catch , as am very new to coding, can anyone please let me know why am getting null pointer Exception.
package ObjectRepository;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class PropertiesGuru99Bank {
WebDriver driver;
#Test
public void f() {
File file=new File("E:\\selenium\\Rahul\\Project\\src\\ObjectRepository\\object.properties");
FileInputStream f=null;
try {
f=new FileInputStream(file);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
Properties prop=new Properties();
try {
prop.load(f);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
driver.get(prop.getProperty("url"));
driver.findElement(By.id(prop.getProperty("id"))).sendKeys("rahul");
}
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "E:\\selenium\\lib\\chromedriver_win32\\chromedriver.exe");
new ChromeDriver();
}
#AfterTest
public void afterTest() {
}
}

Small typo probably. You are not instantiating the driver. new ChromeDriver(); does not instantite the driver. do driver = new ChromeDriver(); or shown below after setting the driver exe to system property.
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class PropertiesGuru99Bank {
WebDriver driver;
#Test
public void f() {
File file=new File("E:\\selenium\\Rahul\\Project\\src\\ObjectRepository\\object.properties");
FileInputStream f=null;
try {
f=new FileInputStream(file);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
Properties prop=new Properties();
try {
prop.load(f);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getStackTrace());
}
driver.get(prop.getProperty("url"));
driver.findElement(By.id(prop.getProperty("id"))).sendKeys("rahul");
}
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver", "E:\\selenium\\lib\\chromedriver_win32\\chromedriver.exe");
//this is what you are missing
driver = new ChromeDriver();
}
#AfterTest
public void afterTest() {
}
}

Related

io.github.bonigarcia.wdm.WebDriverManagerException: chromedriver 88.0.4324.150 for WIN64 not found in https://chromedriver.storage.googleapis.com/

It seems like my chromedriver is not updated by the below code:
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import testone2.firstTest;
import java.io.*;
public class testLogin {
protected WebDriver driver;
private int seconds;
public testLogin() {
super();
}
#BeforeTest
public void beforeTest() {
//Download the web driver executable
String chromeVersion = null;
try {
FileReader reader = new FileReader("chromeVersion.txt");
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
chromeVersion = line.trim();
}
reader.close();
} catch (IOException e) {
Throwable ioException = new Throwable();
ioException.printStackTrace();
}
WebDriverManager.chromedriver().version(chromeVersion).setup();
boolean oldVersion = false;
try {
driver = new ChromeDriver();
} catch (Exception e) {
oldVersion = false;
String err = e.getMessage();
chromeVersion = err.split("version is")[1].split("with binary path")[0].trim();
try {
FileWriter writer = new FileWriter("chromeVersion.txt", true);
writer.write(chromeVersion);
writer.close();
} catch (IOException er) {
}
}
if (!oldVersion) {
WebDriverManager.chromedriver().version(chromeVersion).setup();
driver = new ChromeDriver();
}
}
public void sleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Chrome is Version 88.0.4324.182 (Official Build) (64-bit)
and WebDriverManager dependency is 4.2.2
This is returned in console:
io.github.bonigarcia.wdm.WebDriverManagerException: io.github.bonigarcia.wdm.WebDriverManagerException: chromedriver 88.0.4324.150 for WIN64 not found in https://chromedriver.storage.googleapis.com/
Can anyone point out if its the code to read version of chromedriver at fault? What is the problem here?
Thanks
Solved by setting chromeversion.txt to 88.0.4324.96

Selenium program returning NoSuchElementException no matter what element query type I use?

I have a stock data site that I am trying to use Selenium to parse data from. I feel like I'm really close, but something in my code is causing the program to return a NoSuchElementException. I can do a JS query of the page (https://www.cnbc.com/quotes/?symbol=.DJI) using my desired element from the Chrome developer console as follows:
document.getElementsByClassName("last original ng-binding")
However, doing a similar query in my Java-based Selenium program to find the element by class name returns this exception. Why that be when I'm using the same class name as the JS query? I've tried doing queries by xpath and css as well with a similar error. Here's my code I have:
//Built in Java 1.7 due to Selenium compatabilities
//Import packages
import java.io.File;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.By.ByClassName;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Tester {
//Instantiate common variables
WebDriver driver;
String url;
Scanner input;
boolean error;
int uses = 0;
public void invokeBrowser() {
try {
//Point Selenium to Chrome Driver file
File file = new File("C:\\Users\\zrr81\\eclipse-workspace\\WebScraper\\Selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
//Initialize Chrome driver and perform maintenance functions
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
uses ++;
//Execute parseData code
parseData();
} catch (Exception e) {
e.printStackTrace();
}
}
//Try to connect, include catch for typos/errors
public void parseData() {
try {
input = new Scanner(System.in);
System.out.println("Enter the url you would like to connect to: ");
String url = input.nextLine();
driver.get(url);
elementLocator();
}
//Specific catch for an invalid site (e.g. a dead link)
catch(InvalidArgumentException e) {
System.out.println("He's dead Jim! :/");
}
//Catch for all other exceptions
catch(Exception ex) {
System.out.println("Check your syntax partner!");
}
}
public void elementLocator() {
try {
//driver.findElement(By.linkText("DJIA</a>")).click();
String stock = driver.findElement(By.className("last original ng-binding")).toString();
System.out.println(stock);
//Catch specific exception for html element not found
} catch (NoSuchElementException e) {
System.out.println("Selected element not found");
error = true;
//General exception catch
} catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (error==true) {
closeBrowser();
}
}
}
public void closeBrowser() {
//If only 1 window is open, close the window
if(uses == 1) {
driver.close();
}
//Otherwise, close the whole browser
else {
driver.quit();
}
}
//Invoke methods
public static void main(String[] args) {
Tester myObj = new Tester();
myObj.invokeBrowser();
}
}
NoSuchElement exception occurs when element is not present on the web page for procession during Runtime. Also , your findElement is wrong in your code. Please refer below code to print 23,433.57 from your webpage.
WebElement TxtBoxContent = driver.findElement(By.cssSelector("td > .last:nth-child(1)"));
System.out.println("Text " +TxtBoxContent.getText());

FileOutputStream doesn't show FileNotFoundException

for FileOutputStream, it will throw a FileNotFoundException if the file doesn't exist, but it will create it if it can.
I dont have a Sample.txt in my project root
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream s= new FileOutputStream("Sample.txt");
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
The problem is:
I cannot see the Output of the "File Not Found" from the Terminal. How did it happen?
Thank you
You can set Sample.txt as a File first and check if it exists with .canWrite()
You still have to put a try/catch around FileOutputStream, but it should never go in the catch block.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) {
File f = new File("Sample.txt");
if (!f.exists()) {
System.out.println("File not Found");
}
else {
try {
FileOutputStream s = new FileOutputStream(f);
} catch (FileNotFoundException e) {}
}
}
}

How to resolve the SessionID=null issue when running the test case from testng.xml

My issue is similar to this-
SessionNotFoundException: Session ID is null. Using WebDriver after calling quit()? (Selenium)
When i run the test cases individually it runs fine but when i run them from testng.xml 2nd test case onward everything fails due to session id being null. I have been looking around for solution and figured the issue is with scoping of driver. Can anybody tell me what is the best way to solve this?
This is what my framework looks like-
TestCase
package testCase;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import utility.Constant;
import utility.OpentapWrappers;
import utility.Reporter;
public class TC001 extends OpentapWrappers{
#Test (description="Test")
public void main() {
WebDriverWait wait=new WebDriverWait(driver, 60);
try {
wait.until(ExpectedConditions.urlContains(Constant.Plumbing_URL));
/* Validate navigation to Plumbing */
ValidateUrl(Constant.Plumbing_URL);
} catch (NoSuchElementException e) {
e.printStackTrace();
Reporter.reportStep("NoSuchElementException" , "FAIL");
}
}
#BeforeClass
public void beforeClass(){
browserName="firefox";
testCaseName = "TC001";
testDescription = "Validate Header";
}
}
ReusableActions
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import utility.Reporter;
public class ReusableActions {
public static WebDriver driver;
public ExtentReports extent;
public static ExtentTest test;
/* Invoke Browser and enter the URL */
public static void InvokeApp(String browser, String url) {
try {
if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
} else {
System.setProperty("webdriver.gecko.driver", "D:\\geckodriver.exe");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("acceptInsecureCerts",true);
driver = new FirefoxDriver(capabilities);
}
//driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(url);
Reporter.reportStep("The browser :" +browser+ " is launched with URL :" +url+ "successfully","PASS");
} catch (Exception e) {
e.printStackTrace();
Reporter.reportStep("The browser :" +browser+ " could not be launched with URL :" +url+ "successfully","FAIL");
}
}
/* Validate URL*/
public static void ValidateUrl(String URL){
try {
if (driver.getCurrentUrl().contains(URL)) {
Reporter.reportStep("Page is successfully loaded :"+URL, "PASS");
} else {
Reporter.reportStep("Page Title :"+driver.getCurrentUrl()+" did not match with :"+URL, "FAIL");
}
} catch (Exception e) {
e.printStackTrace();
Reporter.reportStep("The URL did not match", "FAIL");
}
}
/* Quit Browser*/
public void quitBrowser() {
try {
driver.quit();
} catch (Exception e) {
Reporter.reportStep("The browser could not be closed.", "FAIL");
}
}
}
Reporter Class
public class Reporter extends OpentapWrappers{
private static ExtentTest test;
private static ExtentReports extent;
public static void reportStep(String desc, String status) {
long number = (long) Math.floor(Math.random() * 900000000L) + 10000000L;
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(src, new File("D:\\Reports\\Screenshots\\Scr_"+number+".png"));
} catch (WebDriverException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Write if it is successful or failure or information
if (status.toUpperCase().equals("PASS")) {
test.log(LogStatus.PASS, desc + test.addScreenCapture(".\\Screenshots\\Scr_"+number+".png"));
} else if (status.toUpperCase().equals("FAIL")) {
test.log(LogStatus.FAIL, desc + test.addScreenCapture(".\\Screenshots\\Scr_"+number+".png"));
throw new RuntimeException("FAILED");
} else if (status.toUpperCase().equals("INFO")) {
test.log(LogStatus.INFO, desc);
}
}
public static void startResult() {
extent = new ExtentReports("D:\\Reports\\SiteCoreUS.html", false);
extent.loadConfig(new File("D:\\extentreports-java-2.41.2\\extent-config.xml"));
}
public static void startTestCase() {
test = extent.startTest(testCaseName, testDescription);
}
public static void endResult() {
extent.endTest(test);
extent.flush();
}
}
OpenTapWrapper Class
package utility;
public class OpentapWrappers extends ReusableActions {
protected static String browserName;
protected static String testCaseName;
protected static String testDescription;
#BeforeSuite
public void beforeSuite() throws FileNotFoundException, IOException {
Reporter.startResult();
}
#BeforeMethod
public void beforeMethod() {
Reporter.startTestCase();
InvokeApp(browserName,Constant.SiteCoreUSURL);
}
#AfterSuite
public void afterSuite() {
Reporter.endResult();
}
#AfterMethod
public void afterMethod() {
quitBrowser();
}
}
You have a lot of complications in your code, the biggest one among them being you having a static reference to ReusableActions#driver. So what happens here is that all the sub-classes of ReusableActions viz., your TC001 end up sharing the same static data member of driver. This is causing a race condition for you.
So when you run two or more #Test methods in parallel they end up sharing the same static WebDriver reference. I guess that is what is causing the problem because one of your #Test method runs to completion very fast and it calls the quit() method on the driver object. Now when the second test method reaches the quit() call, it ends up calling the quit() second time.
Please remove the static references in your entire code.
I also would suggest that you trim down the layers of inheritance that you have in your code. It adds complexity to your code and makes debugging difficult. You might want to favor composition over inheritance.
Take a look at this blog post that I created, wherein you can achieve the same sort of parallel execution for your webdriver tests but by using composition rather than inheritance.

about classpath in run configuration in eclipse

Test1_Exec.java
import java.io.IOException;
public class Test1_Exec {
public static void main(String[] args) throws IOException {
Runtime run = Runtime.getRuntime();
try {
Process p = run.exec("java -cp bin Test1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Test1.java:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void main(String[] args)
{
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Test1_Exec.class and Test1.class are both in the bin folder under JavaTest(project name), and the codes do work. But I want to replace the code "Process p = run.exec("java -cp bin Test1")" with "Process p = run.exec("java Test1")" by adding bin folder( right clikcing JavaTest(project name)->Run As->Run Configuration | Tab Classpath --- User Entries --- Advanced --- Add Folders ), then Test1.txt is not created by new codes. So where is the problem ?
To me program seemed unnecessarily complex. Why not below(if you dont have specific requirement)
import java.io.IOException;
public class Test1_Exec {
public static void main(String[] args) throws IOException {
try {
Test1.createFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void createFile()
{
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources