Getting Null pointer exception while running my code - selenium

I am getting the null pointer error in the below code. If you run the code it will execute all the code just before the code where i mentioned 'captureScreenshot()' function after this its not executing.
package rough;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestEmailAndScreenshot1 {
public static WebDriver dr;
public static String mailscreenshotpath;
public static void captureScreenshot(){
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int sec = cal.get(Calendar.SECOND);
int min = cal.get(Calendar.MINUTE);
int date = cal.get(Calendar.DATE);
int day = cal.get(Calendar.HOUR_OF_DAY);
File scrFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
try {
mailscreenshotpath = System.getProperty("user.dir")+"\\screenshot\\"+year+"_"+date+"_"+(month+1)+"_"+day+"_"+min+"_" +sec+".jpeg";
FileUtils.copyFile(scrFile, new File(mailscreenshotpath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
WebDriver dr=new FirefoxDriver();
dr.manage().window().maximize();
dr.manage().timeouts().implicitlyWait(10L, TimeUnit.SECONDS);
dr.get("http://gmail.com");
dr.findElement(By.id("Email")).sendKeys("vijenderchhoker92");
captureScreenshot();
System.out.println(" Screenshot taken successfully....");
}
}

When you do
WebDriver dr = new FirefoxDriver();
In main you hide the public static WebDriver dr; variable, so in captureScreenshot() method it's still null and you get the error trying to use it. Change to
public static void main(String[] args) {
dr = new FirefoxDriver();
dr.manage().window().maximize();
//...
}

Related

Could you help me with what the error is?

import static org.junit.Assert.;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class excel {
WebDriver driver;
#Before public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\IVS Files\Selenium\Drivers\chromedriver v2.43\chromedriver.exe"");
driver.get("http://10.82.180.36/Common/Login.aspx");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5000,TimeUnit.MILLISECOND);
}
#After public void tearDown() throws Exception {
driver.close();
}
#Test public void test() throws
IOException, InterruptedException {
driver.findElement(By.id("body_txtUserID")).sendKeys("donhere");
driver.findElement(By.id("body_txtPassword")).
sendKeys("don#123");
driver.findElement(By.xpath("//[#id="body_btnLogin "]")).click();
driver.findElement(By.id("GeneralTabMenu_pnlCustomer_TopMenu")).click();
String path ="https://infosystechnologies-my.sharepoint.com/personal/doddi_suvarna_ad_infosys_com/Documents/Book1.xlsx";
FileInputStream file = new FileInputStream(path);
XSSFWorkbook book = new XSSFWorkbook(file);
XSSFSheet sheet1 = book.getSheetAt(0);
int rowcount = sheet1.getFirstRowNum();
System.out.println(rowcount);
for (int i = 0; i <= sheet1.getLastRowNum(); i++) {
double loanamount =sheet1.getRow(i).getCell(0).getNumericCellValue();
int month =(int) sheet1.getRow(i).getCell(1).
getNumericCellValue();
String la = String.valueOf(loanamount);
String m = String.valueOf(month);
Thread.sleep(5000);
WebElement name =driver.findElement(By.id("body_cph_Loans_ddlLoanName"));
Select name1 = new Select(name);
name1.selectByIndex(1);
Thread.sleep(5000);
driver.findElement(By.id("body_cph_Loans_txtReqLoanAmount")).sendKeys(la);
driver.findElement(By.id("body_cph_Loans_txtNoOfEMI")).sendKeys(m);
driver.findElement(By.id("body_cph_Loans_btnViewEMI")).click();
String abc =driver.findElement(By.id("body_cph_Loans_lblEMIAmountText")).getText();
driver.findElement(By.id("body_cph_Loans_btnReset")).click();
}
}
}
driver.get("http://10.82.180.36/Common/Login.aspx");
driver = new ChromeDriver();
You should first create object and then launch url...
driver = new ChromeDriver();
driver.get("http://10.82.180.36/Common/Login.aspx");

Where the property key name for the chromedriver has been determined and where it is getting utilized in Selenium?

We usually set the system property for the chromedriver exe using the below code
System.setProperty("webdriver.chrome.driver",path of the chromedriver.exe)
How the property key name is determined as "webdriver.chrome.driver"?
Where the property is utilized in Webdriver wire protocol(Any particular class file for reference)?
Hi i have write utils class for that
You can open browser/navigate url/close browser and etc
package utils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class TestApp {
private WebDriver driver;
private static TestApp myObj;
// public static WebDriver driver;
utils.PropertyFileReader property = new PropertyFileReader();
public static TestApp getInstance() {
if (myObj == null) {
myObj = new TestApp();
return myObj;
} else {
return myObj;
}
}
//get the selenium driver
public WebDriver getDriver()
{
return driver;
}
//when selenium opens the browsers it will automatically set the web driver
private void setDriver(WebDriver driver) {
this.driver = driver;
}
public static void setMyObj(TestApp myObj) {
TestApp.myObj = myObj;
}
public void openBrowser() {
//String chromeDriverPath = property.getProperty("config", "chrome.driver.path");
//String chromeDriverPath = property.getProperty("config", getChromeDriverFilePath());
System.setProperty("webdriver.chrome.driver", getChromeDriverFilePath());
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void navigateToURL() {
String url =property.getProperty("config","url");
driver.get(url);
}
public void closeBrowser()
{
driver.quit();
}
public WebElement waitForElement(By locator, int timeout)
{
WebElement element = new WebDriverWait(TestApp.getInstance().getDriver(), timeout).until
(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private String getChromeDriverFilePath()
{
// checking resources file for chrome driver in side main resources
URL res = getClass().getClassLoader().getResource("chromedriver.exe");
File file = null;
try {
file = Paths.get(res.toURI()).toFile();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
}
enter code here

getWindowHandle() throws error message "Nullpointerexception"

this is a simple selenium function that is trying to get a windowhandle.
right at that statement it throws" Nullpointerexception"
import static org.junit.Assert.*;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandles {
WebDriver achromeDriver;
String abaseUrl;
public void setUp() throws Exception {
abaseUrl = "http://letskodeit.teachable.com/pages/practice";
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
achromeDriver = new ChromeDriver();
achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
achromeDriver.manage().window().maximize();;
System.out.println("setup completed");
}
#Test
public void test() {
try{
String aparentwindowHandle = achromeDriver.getWindowHandle();
System.out.println("the parent window handle is "+ aparentwindowHandle);
WebElement aopenwindowelementbutton = achromeDriver.findElement(By.id("openwindow"));
aopenwindowelementbutton.click();
String achildwindowhandle = achromeDriver.getWindowHandle();
System.out.println("the child window handle is: " + achildwindowhandle);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A bit more details about your usecase and your observation would have helped us to debug the issue in a better way. However, it seems as you are using the junit framework and in-absence of any of the annotations the setUp() method is never executed.
As the test() method is annotated with #Test the program reaches there with achromeDriver as Null
Solution
A quick solution would be to add #Before annotation to setUp() method as follows:
#Before
public void setUp() throws Exception {
abaseUrl = "http://letskodeit.teachable.com/pages/practice";
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\ChromeDirver\\chromedriver.exe");
achromeDriver = new ChromeDriver();
achromeDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
achromeDriver.manage().window().maximize();;
System.out.println("setup completed");
}

Need to take full webpage screen shot of www.flipkart.com using webdriver

I need to capture the entire webpage of www.flipkart.com using web driver.
I have written the below code for the same. But its not working. Please suggest.
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class ScreenShot {
public static WebDriver driver = null;
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("webdriver.gecko.driver","C:\\Eclipse\\Drivers\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.flipkart.com/");
Thread.sleep(10000);
//Take the screenshot of the entire home page and save it to a png file
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver);
//Screenshot screenshot = new AShot().takeScreenshot(driver, driver.findElement(By.xpath(".//*[#id='container']")));
ImageIO.write(screenshot.getImage(), "PNG", new File("C:\\Users\\Vishvambruth JT\\Desktop\\home.png"));
driver.quit();
}
}
try once with below code.
public class Flipcart {
public WebDriver d;
Logger log;
#Test
public void m1() throws Exception
{
try
{
d=new FirefoxDriver();
d.manage().window().maximize();
d.get("https://www.flipkart.com/");
String pagetitle=d.getTitle();
}
catch(Exception e)
{
System.out.println("something happened, look into screenshot..");
screenShot();
}
}
public void screenShot() throws Exception
{
Files.deleteIfExists(Paths.get("G:\\"+"Test results.png"));
System.out.println("previous pics deleted...");
File scrFile = ((TakesScreenshot)d).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile,new File("G:\\"+"Test results.png"));
}
}

JUnit Parallel Testing

I'm trying to run a piece of code that I found online to run JUnit test in parallel but the only thing I've modified is the URL to hit my local host. Problem is I'm constantly getting the following error and even though I've setup selenium grid many times and know how to set paths etc. I don't know how to fix this one.
org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.ie.driver system property; for more information, see http://code.google.com/p/selenium/wiki/InternetExplorerDriver.
here's the code
package AutomationFrameWork;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;
public class Parallelized extends Parameterized {
private static class ThreadPoolScheduler implements RunnerScheduler {
private ExecutorService executor;
public ThreadPoolScheduler() {
String threads = System.getProperty("junit.parallel.threads", "16");
int numThreads = Integer.parseInt(threads);
executor = Executors.newFixedThreadPool(numThreads);
}
#Override
public void finished() {
executor.shutdown();
try {
executor.awaitTermination(10, TimeUnit.MINUTES);
} catch (InterruptedException exc) {
throw new RuntimeException(exc);
}
}
#Override
public void schedule(Runnable childStatement) {
executor.submit(childStatement);
}
}
public Parallelized(Class<?> klass) throws Throwable {
super(klass);
setScheduler(new ThreadPoolScheduler());
}
}
package AutomationFrameWork;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
#RunWith(Parallelized.class)
public class JUnitParallel {
private String platform;
private String browserName;
private String browserVersion;
private WebDriver driver;
#Parameterized.Parameters
public static LinkedList<String[]> getEnvironments() throws Exception {
LinkedList<String[]> env = new LinkedList<String[]>();
env.add(new String[]{Platform.WINDOWS.toString(), "chrome", "27"});
env.add(new String[]{Platform.WINDOWS.toString(),"firefox","20"});
env.add(new String[]{Platform.WINDOWS.toString(),"ie","11"});
env.add(new String[]{Platform.WINDOWS.toString(),"safari","5.1.7"});
//add more browsers here
return env;
}
public JUnitParallel(String platform, String browserName, String browserVersion) {
this.platform = platform;
this.browserName = browserName;
this.browserVersion = browserVersion;
}
#Before
public void setUp() throws Exception {
DesiredCapabilities capability = new DesiredCapabilities();
capability.setCapability("platform", platform);
capability.setCapability("browser", browserName);
capability.setCapability("browserVersion", browserVersion);
capability.setCapability("build", "JUnit-Parallel");
capability.setCapability("InternetExplorerDriverServer.IE_ENSURE_CLEAN_SESSION",true);
System.setProperty("webdriver.ie.driver",
"C:\\Users\\path to driver\\IEDriverServer.exe");
driver = new RemoteWebDriver(
new URL("http://localhost:7777".concat("/wd/hub")),
capability
);
}
#Test
public void testSimple() throws Exception {
driver.get("http://www.google.com");
String title = driver.getTitle();
System.out.println("Page title is: " + title);
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("BrowserStack");
element.submit();
driver = new Augmenter().augment(driver);
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcFile, new File("Screenshot.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}