Webdriver TestNG NullPointer Exception - java

I am trying to run TestNG testcases which are InterDependent say in a Travel site Test cases are 1st) Login 2nd) Booking 3rd) Cancellation etc.
I am facing 'NullPointer exception' on When Webdriver is Called on 2nd Test..
Any Idea as I have also declared Driver as public static.
I am reading the Locators from a Properties File.
Is It a TestNG bug ?
Here's my Code, Please Scroll Down to see the Pointer exception..
public class LoginTest {
public static WebDriver driver;
public static Properties p;
public static FileInputStream f ;
#Test
public void loginTest() {
System.out.println("Enter LoginTest");
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebDriver driver = new FirefoxDriver();
driver.get("https://in3.seatseller.travel/");
driver.manage().window().maximize();
// Login Process Starts here ..
try{
driver.findElement(By.name(p.getProperty("login.username.textfield"))).sendKeys("user");
driver.findElement(By.name(p.getProperty("login.password.textfield"))).sendKeys("password");
WebElement ele =driver.findElement(By.id(p.getProperty("login.signin.button")));
ele.click();
/*String classValue = ele.getAttribute("class");*/
}
catch (Exception e) {
}
}
#Test (dependsOnMethods={"loginTest"})
public void booking() throws InterruptedException{
System.out.println("Enter Booking");
// Type Bangalore on Source Field..
Properties p=new Properties();
FileInputStream f = null;
try {
f = new FileInputStream("D:\\BOSSFramework\\Framework\\locators.properties");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.load(f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*Null Pointer is on Below Line*/
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(p.getProperty("oneapp.source.textfield"))));
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys("Bangalore");
driver.findElement(By.xpath(p.getProperty("oneapp.source.textfield"))).sendKeys(Keys.TAB);
Thread.sleep(900L);

The issue is that you're declaring WebDriver driver in loginTest(), then trying to reference the loginTest() instance of driver in booking().
If you modify loginTest() as follows, it should work:
driver = new FirefoxDriver();

Related

Testing different scenarios using one browser instance in java, selenium, cucumber and JUnit runner

There is an application am working on where the process of logging in takes far too long, am looking for a way of executing all scenarios and multiple features with one chrome driver instance.
Here is my hooks code
#Before(order = 0)
public void launchbrowser() {
reader = new ConfigFileReader();
pro = reader.ConfigFile();
try {
BaseClass.setUp();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#After
public void tearDown(Scenario scenario) {
File destPath;
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy_hh.mm.ss");
Date curDate = new Date(); String strDate = sdf.format(curDate);
File screenshot_with_scenario_name = (((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE));
if(scenario.isFailed())
{
destPath=new File("./test-output/Screenshots/Failed/" + scenario.getName()+ strDate + ".png");
}
else{
destPath=new File("./test-output/Screenshots/Passed/" + scenario.getName()+ strDate + ".png");
}
try {
FileUtils.copyFile(screenshot_with_scenario_name,destPath);
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
BaseClass.Closebrowser();
}
And here is Baseclass where driver is setup
public static void setUp() throws Exception {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
jse = (JavascriptExecutor) driver;
}
#Maxwell Maragia you can try using global hooks #BeforeAll and #AfterAll. You can find the details here https://cucumber.io/docs/cucumber/api/?lang=java

How to pass error message from method causing exception to onTestFailure method in Listener

I am trying to print exception message from method which causing exception to testng listener so that I can print it in extent report. I have written code like this
#Override
public void onTestFailure(ITestResult result) {
String screenshotPath = "";
try {
screenshotPath = ScreenshotUtil.capture();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
test2.log(Status.FAIL, MarkupHelper.createLabel("Error occured", ExtentColor.RED));
test2.addScreenCaptureFromPath(screenshotPath, "Error");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and I am throwing exception in below method
public HomePage assertLoginSuccessful(boolean flag, String name) throws ExplicitAssertionError, IOException{
waitForPageToLoad();
WebDriverWait wait=new WebDriverWait(getDriver(), 5);
String xpath="//a[#id='welcome'][contains(.,'Welcome "+name+"')]";
try{
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(xpath)));
if (flag){
List<WebElement> list=getDriver().findElements(By.xpath(xpath));
if (list.size()==0){
throw new ExplicitAssertionError("User name"+name+" not found hence login not successful");//this message should be passed to listener
}
}
}catch (Exception ex){
throw new ExplicitAssertionError("User name"+name+" not found hence login not successful");
}
return this;
The interface ITestResult contains a method getThrowable to access the exception you are throwing in your test.
You can add the following code to onTestFailure:
if (null != result.getThrowable()) {
String msg = result.getThrowable().getMessage();
}

Next method not executing after the main method

I have to files out of which the first file contains login details. First file is loginDetailsClass.java and below is the code in the file.
public class loginDetailsClass {
#SuppressWarnings("deprecation")
public static void browserLaunch() {
WebDriver driver;
String baseurl = "https://www.facebook.com/";
System.setProperty("webdriver.chrome.driver","D:\\eclipse-workspace\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
options.addArguments("--disable-infobars");
capabilities.setCapability("chrome.binary","D:\\eclipse-workspace\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
//Login section
try {
Thread.sleep(7000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement usnfield = driver.findElement(By.id("email"));
usnfield.sendKeys("alex");
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement pwdfield = driver.findElement(By.id("pass"));
pwdfield.sendKeys("alex42");
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement lgn_btn = driver.findElement(By.id("u_0_8"));
lgn_btn.click();
}
}
And the second file is facebookClass.java and below is the code in the file.
public class facebookClass {
static WebDriver driver;
#Test(priority = 0)
public static void main(String[] args) {
loginDetailsClass.browserLaunch(); //function called from loginDetailsClass.java page
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
#Test(priority = 1)
public static void searchfriends() {
//Switching to iFrame for locating elements
driver.switchTo().frame(driver.findElement(By.id("contentFrame")));
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
//Searching a friend using friend name field
WebDriverWait wait = new WebDriverWait (driver, 20);
WebElement friendName = wait.until(ExpectedConditions.elementToBeClickable(By.id("txtFriendName")));
friendName.sendKeys("James");
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement clck_Search = driver.findElement(By.id("btnSearch"));
clck_Search.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement select_friend = driver.findElement(By.xpath("//*[#id=\"trFriend_3\"]"));
select_friend.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
//Switching back to main frame from iFrame
driver.switchTo().defaultContent();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
#Test(priority = 2)
public static void logout() {
//Logout
WebElement logout = driver.findElement(By.xpath("/html/body/form/table/tbody/tr[1]/td/div/div[8]/table/tbody/tr/td[2]"));
logout.click();
try {
Thread.sleep(7000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
driver.close();
}
}
While executing facebookClass.java, login method is called properly and login is successful. But from public static void searchfriends() method, execution doesn't works further. At the very first days all methods got executed successfully. But from the next day it now working.

java, selenium web driver

This is the snapshot of Login popup :
I'm newbie in Selenium webdriver. I wrote this code to figure out navigate commands but once the browser opens, there is a login popup that is displayed. I tried to close it using classname or xpath but timeout exception occurs.
Do I need to use explicit wait in this case? Could you help me to figure out what the problem is?
public class TestNavigateCommands {
WebDriver driver;
public void invokeBrowser(){
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
ChromeOptions options=new ChromeOptions();
options.addArguments("start-fullscreen");
driver=new ChromeDriver(options);
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
navigateCommands();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void navigateCommands(){
try {
driver.navigate().to("https://www.flipkart.com/");
Thread.sleep(4000);
driver.findElement(By.className("2AkmmA _29YdH8")).click();
//driver.findElement(By.xpath("//*[#class='_2AkmmA _29YdH8']")).click();
driver.findElement(By.xpath("//span[starts-with(text(),'Applicances')]")).click();
driver.findElement(By.xpath("//span[contains(text(),'Microwave Ovens')]")).click();
Thread.sleep(2000);
driver.navigate().back();
Thread.sleep(2000);
driver.navigate().forward();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
TestNavigateCommands test1= new TestNavigateCommands();
test1.invokeBrowser();
}
}
Exception :
[43.366][SEVERE]: Timed out receiving message from renderer: 37.150
[43.373][SEVERE]: Timed out receiving message from renderer: -0.007
org.openqa.selenium.TimeoutException: timeout
Try this code it may help:
public class TestNavigateCommands {
public static void main(String[] args) throws InterruptedException {
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver,50 );
driver.manage().window().maximize();
driver.navigate().to("https://www.flipkart.com/");
driver.findElement(By.xpath("//button[contains(#class,'YdH8')]")).click();
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[#title='Appliances']//span"))));
driver.findElement(By.xpath("//a[#title='Appliances']//span")).click();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestNavigateCommands {
WebDriver driver;
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver", "/Users/himaja/Documents/chromedriver");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-fullscreen");
driver = new ChromeDriver(options);
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
navigateCommands();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void navigateCommands() {
try {
driver.navigate().to("https://www.flipkart.com/");
driver.findElement(By.xpath("//div[#class='_3Njdz7']//button[#class='_2AkmmA _29YdH8']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a[#title='Appliances']//span"))));
driver.findElement(By.xpath("//a[#title='Appliances']//span")).click();
Thread.sleep(2000);
driver.navigate().back();
driver.navigate().forward();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Android static vs nonstatic issue

I've been trying to call the following:
public static void startfile() {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get an error that tells me that "Cannot make a static reference to the non-static method openFileOutput(String, int) from the type ContextWrapper"
So I searched for that error and found this site.
I implemented this:
public static void startfile(Trackfile O) {
Log.i("File Works", "working2 ");
O.nonstatstartfile();
}
public void nonstatstartfile(){
Log.i("File Works", "nonStat");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I call startfile from another class getting a Null pointer error. What argument do I need to send to avoid the null pointer error?
You can pass context from activity like below
public static void startfile(Context c) {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = c.openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void startfile() {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add this method to your class, and use it without problems.
If you need it in main class, use it over object.

Categories