I am new to the selenium automation world, Getting java.lang.NullPointerException
error which trying to call the function to take a screenshot in a test method on Selenium. I am pretty sure I have missed initialize or return the driver somewhere. below is the code.
baseTest class where I am initializing the webdriver
public class baseTest {
public Properties objProp = new Properties();
FileInputStream readProp;
{
try {
readProp = new FileInputStream("C:\\Users\\kiran\\IdeaProjects\\SelProject2\\src\\test\\java\\appDetails.properties");
objProp.load(readProp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected WebDriver driver;
@BeforeClass
public void beforeSuite()
{
System.setProperty(objProp.getProperty("browser"),objProp.getProperty("driverPath"));
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(objProp.getProperty("URL"));
}
@AfterSuite
public void afterSuite()
{
if(null != driver)
{
driver.close();
driver.quit();
}
}
public WebDriver getDriver()
{
return driver;
}
}
All my tests extends the baseTest function link shown below
public class loginFunction extends baseTest {
guruLoginPage objLogin;
guruHomePage objHome;
takeScreenshot objSS = new takeScreenshot(driver);
//readExcel readObj;
@Test
public void performLogin() throws IOException, InterruptedException {
objLogin = new guruLoginPage(driver);
String loginPageTitle = objLogin.getTitle();
Assert.assertTrue(loginPageTitle.contains("Demo Site"));
objSS.screenshot();
objLogin.loginAction(objProp.getProperty("appUsername"), objProp.getProperty("appPassword"));
Thread.sleep(2000);
objHome = new guruHomePage(driver);
Assert.assertTrue(objHome.validateLogin().contains("Manger Id : mngr242657"));
Thread.sleep(2000);
objSS.screenshot();
}
}
when i write this piece of code in the loginfunction, it works fine, but when i am trying to optimize and put it in a separate class and call the method I am getting java.lang.NullPointerException
error
public class takeScreenshot{
WebDriver driver;
public takeScreenshot(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements(driver,this);
}
public void screenshot() throws IOException {
String fileSuffix = DateTime.now().toString("yyyy-dd-MM-HH-mm-ss");
TakesScreenshot ss = ((TakesScreenshot)this.driver);
File srcFile = ss.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile,new File("C:\\Users\\kiran\\IdeaProjects\\SelProject2\\src\\test\\java\\Screenshots\\"+fileSuffix+".jpg"));
}
}