I have a framework that uses POM model and I have used a Utils folder structure which has DriverFactory,Constant and ReadConfigFile java files that configures and opens the browser. (code below)
Now before I did this (introducing the Utils package) the code was running fine and after introducing the Utils package i am getting "Unable to load browsernull" exception.
Not sure what is causing the problem. I am using a Mac machine.
Constant.java file:
package Utils;
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties/config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir")+"CucumberFramework/src/test/java/Resources/geckodriver";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir")+"CucumberFramework/src/test/java/Resources/chromedriver";
}
DriverFactory.java file:
package Utils;
//import com.sun.java.util.jar.pack.Instruction;
import com.sun.tools.javac.code.Attribute;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.PageFactory;
import pageObjects.AddIssuePage;
import pageObjects.Login_Page;
import java.util.concurrent.TimeUnit;
public class DriverFactory {
public static WebDriver driver;
public static Login_Page login_page;
public static AddIssuePage addIssuePage;
public WebDriver getDriver() {
try
{
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (null == driver) {
System.setProperty("webdriver.geckodriver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
case "chrome":
if (null == driver) {
System.setProperty("webdriver.chromedriver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
}
break;
}
} catch (Exception e)
{
System.out.println("Unable to load browser" + e.getMessage());
} finally
{
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
login_page = PageFactory.initElements(driver, Login_Page.class);
}
return driver;
}
}
ReadConfigFile.java file:
package Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile () {
try {
ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
}
Stacktrace:
java.lang.NullPointerException
at Utils.DriverFactory.getDriver(DriverFactory.java:63)
at Steps.MasterHooks.setup(MasterHooks.java:11)
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:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
java.lang.NullPointerException
at Utils.DriverFactory.getDriver(DriverFactory.java:63)
at Steps.MasterHooks.setup(MasterHooks.java:11)
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:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Process finished with exit code 1
MasterHooks
package Steps;
import Utils.DriverFactory;
import cucumber.api.java.After;
import cucumber.api.java.Before;
public class MasterHooks extends DriverFactory {
#Before
public void setup() {
driver = getDriver();
}
#After
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
This error message...
Unable to load browsernull
...implies that the function getBrowser() is returning null.
I would suggest the changes:
In ReadConfigFile.java:
Change:
ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
To:
File src = new File(Constant.CONFIG_PROPERTIES_DIRECTORY);
FileInputStream fis = new FileInputStream(src);
Properties prop = new Properties();
prop.load(fis);
Change:
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
To:
public String getBrowser(){
return prop.getProperty("browser");
}
In Constant.java
Change:
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties/config.properties";
To:
public final static String CONFIG_PROPERTIES_DIRECTORY = "./src/main/java/properties/config.properties";
In DriverFactory.java
Change:
"webdriver.geckodriver"
To:
"webdriver.gecko.driver"
Change:
"webdriver.chromedriver"
To:
"webdriver.chrome.driver"
The problem here is that, input instance variable of type Input Stream is assigned to null in Read config file class.
It should be assigned to input stream as given below.
package Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile () {
try {
input = ReadConfigFile.class.getClassLoader ().getResourceAsStream (Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
}
Could you share your properties/config.properties file?
From the infos you shared I was thinking about that:
When, in DriverFactory, you call
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
In the getBrowser() there is:
public String getBrowser(){
if (prop.getProperty("browser") == null)
return " ";
return prop.getProperty("browser");
}
So, if prop.getProperty("browser") is null, you are returning " " in browserName.
In the switch:
switch (browserName) {
case "firefox":
if (null == driver) {
System.setProperty("webdriver.geckodriver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
case "chrome":
if (null == driver) {
System.setProperty("webdriver.chromedriver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
}
break;
}
} catch (Exception e)
{
System.out.println("Unable to load browser" + e.getMessage());
} finally
{
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
login_page = PageFactory.initElements(driver, Login_Page.class);
}
I don't see any check in the case browserName is " " or in another case (I mean, there isn't a default case). So, in case browserName is " " or something else different of "firefox" or "chrome" you go directly to the finally statement (the finally is always executed). In this case, because the driver is not instantiated, you will have a nullpointer exception in:
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
Related
I am trying to capture screenshot in Selenium, However I am getting an error on -File source = ts.getScreenshotAs(OutputType.FILE); I have searched the code online and it they have given it as it is. Now I don't know what should be replaced with this code. The error I am getting is- FILE cannot be resolved or is not a field. My full code is:
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.aventstack.extentreports.Status;
import com.google.common.io.Files;
import com.mongodb.MapReduceCommand.OutputType;
public class UtilityMethods extends ExtentReportBaseClass{
static WebDriver driver;
public static WebDriver openBrowser(String browsers) {
System.out.println("initiated browser is " + browsers);
if (browsers.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.firefox.marionette", "");
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability("marionatte", false);
FirefoxOptions opt = new FirefoxOptions();
opt.merge(dc);
driver = new FirefoxDriver(opt);
}
else if (browsers.equalsIgnoreCase("Chrome")) {
// String driverPath = System.getProperty("user.dir") +
// "\\src\\Drivers\\chromedriver";
// System.setProperty("webdriver.chrome.driver", driverPath);
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
return driver;
}
public static void launchWebsite(String URL) {
driver.get(URL);
}
public static By locateByElement(String locator, String locatorValue) {
By by = null;
switch (locator) {
case "id":
by = By.id(locatorValue);
break;
case "name":
by = By.name(locatorValue);
break;
case "linktext":
by = By.linkText(locatorValue);
break;
case "partialLinkText":
by = By.partialLinkText(locatorValue);
break;
case "className":
by = By.className(locatorValue);
break;
case "tagName":
by = By.tagName(locatorValue);
break;
case "cssSelector":
by = By.cssSelector(locatorValue);
break;
case "xpath":
by = By.xpath(locatorValue);
break;
}
System.out.println("value of by is" + by);
return by;
}
public void sendDataById(String locatorValue, String userData) {
driver.findElement(By.id(locatorValue)).sendKeys(userData);
}
public void sendData(String element) {
String[] var = element.split("###");
String loctype = var[0];
String locval = var[1];
// System.out.println(locval);
String uservalue = var[2];
// System.out.println(locval);
// System.out.println(uservalue);
By locator = locateByElement(loctype, locval);
System.out.println(loctype);
System.out.println(locval);
driver.findElement(locator).sendKeys(uservalue);
}
public WebDriver getdriver() {
if (driver == null) {
driver = new FirefoxDriver();
return driver;
} else {
return driver;
}
}
public static String capture(WebDriver driver,String screenShotName) throws IOException
{
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String dest = System.getProperty("user.dir") +"/TestCasesScreenshot"+screenShotName+".png";
File destination = new File(dest);
Files.copy(source, destination);
return dest;
}
public void clickElement(String locElem) throws IOException {
try {
System.out.println(locElem);
String[] var = locElem.split("###");
String loctype = var[0];
String locval = var[1];
System.out.println(loctype);
System.out.println(locval);
By locator = locateByElement(loctype, locval);
driver.findElement(locator).click();
}
catch(Exception e)
{
System.out.println("Catched Exception, Element not found");
String screenShotPath = UtilityMethods.capture(driver, "screenShotName");
test.log(Status.FAIL, "Snapshot below: " + test.addScreenCaptureFromPath(screenShotPath));
}
}
}
You need to import selenium's OutputType. Use this -- import org.openqa.selenium.OutputType. Currently you have a mongodb class import.
I know I can upload file to browser with many ways such as: AutoIt, Robot Class, and other ways(I tried them all and they worked most of time).
I got introduced to Winium and I would like to make the same test case with it, that is, upload a file to a browser using it, but I did not know what to do to switch between web driver to winium driver. Please help because I searched a lot for this trick but could not find any result
package testUtilities;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.winium.WiniumDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class WiniumWeb
{
WebDriver driver;
#BeforeClass
public void setUp() throws IOException
{
driver = new FirefoxDriver();
driver.navigate().to("http://the-internet.herokuapp.com/upload");
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\Resources\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists())
{
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try
{
driver = new WiniumDriver(new URL("http://localhost:9999"), null);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException
{
String file = System.getProperty("user.dir") + "\\Resources\\TestData.csv";
WebElement window = driver.findElement(By.className("File Upload"));
window.findElement(By.className("#32770")).sendKeys(file);
Thread.sleep(2000);
}
}
if you are still finding solution.I am sharing my script which worked for me.
public class FileUpload extends BaseClass {
static WiniumDriver d;
#BeforeClass
public void setUp() throws IOException {
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
LaunchLocalBrowser("chrome","http://the-internet.herokuapp.com/upload");//use your own code to launch browser
driver.findElement(By.id("file-upload")).click();
String WiniumEXEpath = System.getProperty("user.dir") + "\\lib\\Winium.Desktop.Driver.exe";
File file = new File(WiniumEXEpath);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + WiniumEXEpath + " does not exist");
}
Runtime.getRuntime().exec(file.getAbsolutePath());
try {
d = new WiniumDriver(new URL("http://localhost:9999"),options);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testNotePade() throws InterruptedException {
String file = System.getProperty("user.dir") + "\\lib\\Testdata.txt";
d.findElementByName("File name:").sendKeys(file);
d.findElementByXPath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']").click();
driver.findElement(By.id("file-submit")).click();
}
}
File upload using WiniumDriverService by referring to port- 9999. Creating winium instance using free port having issues. Below code is intended for sample implementation of Browser factory to facilitate web and desktop instances.
public class FactoryManager {
public static ClientFactory getIndividualProduct(EnumProductLists product) {
ClientFactory factory = null;
if (null != product) {
switch (product) {
case CHROME:
factory = new ProductChromeClient();
break;
case DESKTOP:
factory = new ProductWiniumClient();
break;
default:
break;
}
}
return factory;
}
}
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
public class ProductWiniumClient extends ClientFactory {
private WiniumDriverService service;
#Override
protected void startService() {
if (null == service) {
service = new WiniumDriverService.Builder()
.usingDriverExecutable(
new File(System.getProperty("user.dir") + "/WiniumFolder/Winium.Desktop.Driver.exe"))
.usingPort(9999).withVerbose(true).buildDesktopService();
try {
service.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void createService() {
startService();
DesktopOptions options = new DesktopOptions();
options.setApplicationPath("C:\\Windows\\System32\\openfiles.exe");
deskClient = new WiniumDriver(service, options);
}
#Override
protected void stopService() {
if (null != service && service.isRunning()) {
service.stop();
}
}
}
public class TestCase1 {
WebDriver webClient;
WiniumDriver deskClient;
ClientFactory lists;
#BeforeTest
public void beforeTest() {
lists = FactoryManager.getIndividualProduct(EnumProductLists.CHROME);
webClient = (WebDriver) this.lists.getClient(WebDriver.class.getTypeName());
lists = FactoryManager.getIndividualProduct(EnumProductLists.DESKTOP);
deskClient = (WiniumDriver) this.lists.getClient("");
}
#Test
public void f() {
if (null != webClient) {
try {
webClient.manage().window().maximize();
webClient.get("https://uploadfiles.io/");
webClient.findElement(By.id("upload-window")).click();
String file = System.getProperty("user.dir") + "\\files\\upload.txt";
deskClient.findElement(By.name("File name:")).sendKeys(file);
deskClient.findElement(By.xpath("//*[#Name='Cancel']//preceding-sibling::*[#Name='Open']")).click();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Client Instance is Null!");
}
}
#AfterTest
public void afterTest() {
}
}
I'm trying to use following code :-
driver.findElement(By.xpath(".//*[#id='attach0']")).sendKeys("first path"+"\n"+"second path""+"\n"third path");
I didn't get result.
you can use AutoIT or JAVA code. Below i have used both for your reference. Try anyone of them
import java.io.IOException;
import org.junit.AfterClass;
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;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AutoITforUpload {
private static WebDriver driver;
private static WebDriverWait waitForElement;
#FindBy(css = "span.btn.btn-success.fileinput-button")
private WebElement Add_files_btn;
#BeforeClass
public static void setUp() {
DesiredCapabilities desicap = new DesiredCapabilities();
System.setProperty("webdriver.chrome.driver", "D:/WorkSpace/Driver/chromedriver.exe");
desicap = DesiredCapabilities.chrome();
driver = new ChromeDriver(desicap);
driver.manage().window().maximize();
driver.get("https://blueimp.github.io/jQuery-File-Upload/");
waitForElement = new WebDriverWait(driver, 30);
}
#Test
public void AutoitUpload() {
// String filepath =
// "D:/Mine/GitHub/BasicProgramLearn/AutoItScript/unnamed.png";
WebElement btn = driver.findElement(By.cssSelector("span.btn.btn-success.fileinput-button"));
String file_dir = System.getProperty("user.dir");
String cmd = file_dir + "\\AutoItScript\\unnamed.png";
System.out.println("File directory is " + file_dir);
try {
// Using ordinary
Thread.sleep(3000);
for(int i=0;i<3;i++) //multiple times upload ;
driver.findElement(By.xpath("//*[#id='fileupload']/div/div[1]/span[1]/input")).sendKeys(cmd);
//use any String Array for multiple files
waitForElement(btn);
btn.click();
Thread.sleep(3000);
System.out.println(file_dir + "/AutoItScript/FileUploadCode.exe");
Runtime.getRuntime().exec(file_dir + "\\AutoItScript\\ChromeFileUpload.exe" + " " + cmd);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
#AfterClass
public static void TearDown() {
try {
Thread.sleep(5000);
driver.quit();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void waitForElement(WebElement vElement) {
waitForElement.until(ExpectedConditions.visibilityOf(vElement));
}
}
The code in AutoIt is
#include<IE.au3>
If $CmdLine[0] < 2 Then
$window_name="Open"
WinWait($window_name)
ControlFocus($window_name,"","Edit1")
ControlSetText($window_name,"","Edit1",$CmdLine[1])
ControlClick($window_name,"","Button1")
EndIf
Hope this gives you an idea
I find it more difficult to get solution for my issue.
Actually i am trying to upload a pdf into a website and i need to open the uploaded file and i need to place a x mark in the document, where another person needs to sign.
I have done with the file upload and now i need to open the uploaded pdf and mark the x mark for signature. The x mark will be placed once you click inside the opened document with your mouse cursor.
I have listed my code below,
Please let me know how to clear this issue.
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Dasenddoc {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://pp.govreports.com.au/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testDasenddoc() throws Exception {
driver.get("https://ppaccounts.govreports.com.au/");
driver.findElement(By.id("UserName")).clear();
driver.findElement(By.id("UserName")).sendKeys("vignesh#eimpact.com.au");
driver.findElement(By.id("Password")).clear();
driver.findElement(By.id("Password")).sendKeys("Viki2607");
driver.findElement(By.id("UserName")).clear();
driver.findElement(By.id("UserName")).sendKeys("vignesh2016#eimpact.com.au");
driver.findElement(By.id("btnLogin")).click();
driver.get("https://ppda.govreports.com.au/");
//Thread.sleep(5000);
//WebDriverWait wait = new WebDriverWait(driver, 15);
//wait.until(ExpectedConditions.titleContains("My Documents - Digital Authenticatiion"));
Thread.sleep(5000);
driver.findElement(By.id("newdoc")).click();
driver.findElement(By.linkText("Send a Document")).click();
driver.findElement(By.name("files")).clear();
driver.findElement(By.name("files")).sendKeys("E:\\Vignesh\\Manual\\Documents\\ITR sample files\\Individual_Tax_Return__03072013022155765.pdf");
driver.findElement(By.xpath("/html/body/div[6]/div/div[2]/div[2]/div[3]/div/form/div[1]/div/div[2]/div/table/tbody/tr/td[4]")).click();
driver.findElement(By.id("Name")).clear();
driver.findElement(By.id("Name")).sendKeys("Vignesh K S");
driver.findElement(By.xpath("/html/body/div[6]/div/div[2]/div[2]/div[3]/div/form/div[1]/div/div[2]/div/table/tbody/tr/td[5]")).click();
driver.findElement(By.id("Email")).clear();
driver.findElement(By.id("Email")).sendKeys("vignesh#eimpact.com.au");
driver.findElement(By.id("Message")).clear();
driver.findElement(By.id("Message")).sendKeys("Hi Clients");
driver.findElement(By.xpath("/html/body/div[6]/div/div[2]/div[2]/div[3]/div/form/div[1]/div/div[2]/div/table/tbody/tr/td[8]/div")).click();
driver.findElement(By.id("PvtMessage")).clear();
driver.findElement(By.id("PvtMessage")).sendKeys("Hi Viki");
driver.findElement(By.id("saveprivatemsg")).click();
driver.findElement(By.id("Continue")).click();
Thread.sleep(10000);
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
I have found multiple answers to this issue but none that seem to help me here. When ever i run my test, I get a NullPointerException. I image it is a simple fix but I can't find it.
Here is my set up class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
public class TestSetUp {
private WebDriver driver;
protected StringBuffer verificationErrors = new StringBuffer();
public WebDriver getDriver() {
return driver;
}
private void setDriver(String type, String url) {
switch (type) {
case Config.FIREFOX_DRIVER:
System.out.println("Setting drivers for Firefox...");
driver = initFireFoxDriver(url);
break;
default:
System.out.print("invalid browser type");
}
}
private static WebDriver initFireFoxDriver(String url) {
System.out.println("Launching Firefox browser...");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to(url);
return driver;
}
#BeforeClass
#Parameters({"type","url"})
public void initializeTestBaseSetup(String type, String url) {
try {
setDriver(type, url);
} catch (Exception e) {
System.out.println("Error....." + Arrays.toString(e.getStackTrace()));
}
}
#AfterClass
public void tearDown() {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
This is my LoginPage class where the error is being thrown:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPage {
private WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
private String getLoginTitle() {
return driver.getTitle();
}
public boolean verifyURL() {
return driver.getCurrentUrl().contains("login");
}
public boolean verifyLoginTitle() {
return getLoginTitle().contains(Config.TITLE + " - Log In");
}
public boolean verifySignInError() {
enterUsername("test");
enterPassword("pass");
clickLogin();
return getErrorMessage().contains("Incorrect Username or Password");
}
public boolean verifyForgotPassword() {
return driver.findElement(Config.FORGOT_PASS_NODE).isDisplayed();
}
public boolean verifyLicencing() {
Config.changeSetting("multi_license", 1, driver);
return driver.findElement(Config.LIC_KEY_NODE).isDisplayed();
}
public boolean verifyCreateAccount() {
Config.changeSetting("user_reg", 0, driver);
if(driver.findElement(Config.CREATE_ACCOUNT_NODE).isDisplayed()) {
return false;
}
else {
Config.changeSetting("user_reg", 1, driver);
}
return driver.findElement(Config.CREATE_ACCOUNT_NODE).isDisplayed();
}
public HomePage signIn(String username, String password) {
enterUsername(username);
enterPassword(password);
clickLogin();
return new HomePage(driver);
}
public void enterUsername(String username) {
WebElement identity = driver.findElement(Config.IDENTITY_NODE);
if(identity.isDisplayed())
identity.sendKeys(username);
}
public void enterPassword(String password) {
WebElement pass = driver.findElement(Config.CREDENTIAL_NODE);
if(pass.isDisplayed())
pass.sendKeys(password);
}
public void clickLogin() {
WebElement loginBtn = driver.findElement(Config.SUBMIT_NODE);
if(loginBtn.isDisplayed())
loginBtn.click();
}
public String getErrorMessage() {
String errorMessage = null;
WebElement errorMsg = driver.findElement(Config.DANGER_NODE);
if(errorMsg.isDisplayed())
errorMessage = errorMsg.getText();
return errorMessage;
}
}
And finally my test case:
import org.junit.Assert;
import org.junit.Before;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
public class LoginPageTest extends TestSetUp {
private WebDriver driver;
#Before
public void setUp() {
driver = getDriver();
}
#Test
public void verifyLoginInFunction() {
System.out.println("Log In functionality being tested...");
LoginPage loginPage = new LoginPage(driver);
try {
Assert.assertTrue("The url is incorrect", loginPage.verifyURL());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Title did not match", loginPage.verifyLoginTitle());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Error message did not match", loginPage.verifySignInError());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("\'Forgot Password?\' link is missing", loginPage.verifyForgotPassword());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Create Account setting not working", loginPage.verifyCreateAccount());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
Assert.assertTrue("Additional Licence Key setting not working", loginPage.verifyLicencing());
} catch (Error e) {
verificationErrors.append(e.toString());
}
HomePage homePage = loginPage.signIn(Config.STUDENT, Config.STUDENTPASS);
try {
Assert.assertTrue("Login did not work", homePage.verifyURL());
} catch (Error e) {
verificationErrors.append(e.toString());
}
}
}
I have been trying and just do not know what is causing the issue.
So, I was just dealing with this same problem and realized this question was asked about 7 years ago. I thought I would share what I have come up with as my solution.
For the instance you are trying to access you are passing a null. You assign a value to something that hasn't been initialized yet which gives you the exception you are seeing :) a null value into the driver loginPage is a no no. First initialize -> then pass value -> happy outputs.
I'm not here to give you a coding lesson as you have proven to show you know what you are doing, but happy coding!