java.lang.NullPointerException in PageObjectModel Project - java

I have two pages, in one everything is fine, but in the other I get java.lang.NullPointerException
What is my mistake? Please help
LoginPage.java - all good
package page;
import Base.Base;;
import paths.LoginPath;
public class LoginPage extends Base {
LoginPath loginPath = new LoginPath();
public void ingresarPagina(){
chromeDriverConnection();
visit(loginPath.url);
maximize();
}
public void iniciarSesion(){
type("Qualityadmin", loginPath.txtUser);
type("pass1", loginPath.txtPass);
}
public void clickEnBoton(){
click(loginPath.btnLogin);
}
}
HomePage.java - I tried placing the chromeDriverConnection() again, but I get the same error
package page;
import Base.Base;
import paths.HomePath;
public class HomePage extends Base {
HomePath homePath = new HomePath();
public void mensajeExitoso() {
String mensaje = getText(homePath.txtMesajeExito);
System.out.println(mensaje);
}
}
Error
java.lang.NullPointerException
at Base.Base.getText(Base.java:35)
at page.HomePage.mensajeExitoso(HomePage.java:12)
at step.HomeStep.mensajeExitoso(HomeStep.java:10)
at stepdefinition.HomeStepDefinition.seMuestraUnMensajeDeExito(HomeStepDefinition.java:11)
at ✽.se muestra un mensaje de exito(file:///D:/Project/aer/features/src/test/resources/features/formulario.feature:22)
Process finished with exit code -1
Base.java - I don't think the error is in the Base class, but I put it anyway
Line 35: return driver.findElement (locator) .getText ();
package Base;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Base {
public WebDriver driver;
public Base(WebDriver driver){
this.driver = driver;
}
public Base() {
}
public WebDriver chromeDriverConnection() {
System.setProperty("webdriver.chrome.driver", "./src/test/resources/drivers/chromedriver.exe");
driver = new ChromeDriver();
return driver;
}
public WebElement findElement(By locator){
return driver.findElement(locator);
}
public String getText(WebElement element){
return element.getText();
}
public String getText(By locator){
return driver.findElement(locator).getText();
}
public void type(String inputText, By locator){
driver.findElement(locator).sendKeys(inputText);
}
public void iniciarSesion(String user, String pass){
}
public void click(By locator){
driver.findElement(locator).click();
}
Double num1 = 20.00;
String num2 = num1.toString();
public void visit(String url){
driver.get(url);
}
public void isDisplayed(By locator){
driver.findElement(locator).isDisplayed();
}
public void maximize(){
driver.manage().window().maximize();
}
}

Related

Cannot invoke By not finding elements on the webpage

Im writing a selenium project from scratch using the PageObject.
The below code is failing because the selenium webdriver is not finding elements on the webpage .
This is the error i get :
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null
DriverBase.java :
In this class i setup the driver
package com.EbankingA11y.base;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import com.EbankingA11y.util.WebListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class DriverBase {
protected static final Logger LOG = (Logger) LogManager.getLogger(WebListener.class);
public static WebDriver driver;
public static Properties prop;
public static FileInputStream fis;
public DriverBase() {
prop = new Properties();
try {
fis = new FileInputStream("C:\\Users\\config.properties");
} catch (FileNotFoundException exception) {
exception.printStackTrace();
LOG.debug(" Error \n " +exception.getStackTrace());
}
try {
prop.load(fis);
} catch (IOException exception) {
exception.printStackTrace();
LOG.debug(" Error \n " +exception.getStackTrace());
}
}
public static void initialization () throws InterruptedException {
System.setProperty("webdriver.chrome.driver", prop.getProperty("WEB_DRIVER_PATH") );
//WebDriverManager.chromedriver().setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setAcceptInsecureCerts(true);
driver = new ChromeDriver(chromeOptions);
driver.manage().window().maximize();
driver.get(prop.getProperty("URL"));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
LoginPage.java
In this class i create all the element on the login page and all methods
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.EbankingA11y.base.DriverBase;
public class LoginPage extends DriverBase {
public LoginPage() {
PageFactory.initElements(DriverBase.driver, this);
}
#FindBy(name="username")
WebElement usernameTextBox;
#FindBy(name="password")
WebElement passwordTextBox;
#FindBy(xpath="//input[#value=\\\"Use 'Enter' to confirm\\\"]")
WebElement submitButton;
#FindBy(xpath="//button[#name='button']")
WebElement languageButton;
#FindBy(name="smsCode")
WebElement tokenTextBox;
public void performLogin () {
//WebDriverWait wait = new WebDriverWait(driver,30);
final String username = prop.getProperty("USERNAME");
final String password = prop.getProperty("PASSWORD");
System.out.println(username);
//wait.until(ExpectedConditions.visibilityOf(this.usernameTextBox));
usernameTextBox.clear();
passwordTextBox.clear();
usernameTextBox.sendKeys(username);
passwordTextBox.sendKeys(password);
submitButton.click();
//wait.until(ExpectedConditions.visibilityOf(this.tokenTextBox));
}
}
LoginPageTests.java :
In this class i write tests and i call methods from LoginPage.java Class
package com.EbankingA11y.testcases;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.EbankingA11y.base.*;
import com.EbankingA11y.pages.LoginPage;
public class LoginPageTest extends DriverBase {
public LoginPageTest() throws IOException {
super();
}
LoginPage loginPage = new LoginPage();
#BeforeTest
public void setup() throws InterruptedException {
initialization();
}
#Test
public void login() {
loginPage.performLogin();
}
}
I found that i have to declare the pages in the before methods after the initilisation ()
public class LoginPageTest extends DriverBase {
public LoginPageTest() throws IOException {
super();
}
// here
LoginPage loginPage;
TokenPage tokenPage;
#BeforeTest
public void setup() throws InterruptedException {
initialization();
//here
loginPage = new LoginPage();
tokenPage = new TokenPage();
}
#Test
public void login() {
tokenPage = loginPage.performLogin();
}
}
This is just worked for me

I am getting null pointer exception in page object class why I am getting NPE

Base class
package resources;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
public class base {
public WebDriver driver;
public Properties property;
public String url= "qwerty";
public WebDriver initializeDriver() throws IOException {
property = new Properties();
FileInputStream file = new FileInputStream("D:\\qwe\\rty\\src\\main\\java\\resources\\data.properties");
property.load(file);
String BrowserName = property.getProperty("browser");
if(BrowserName.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", "D:\qwe\\rty\\chromedriver.exe");
driver = new ChromeDriver();
}
else if(BrowserName.equals("firefox"))
{
driver = new FirefoxDriver();
}
else if(BrowserName.equals("IE"))
{
//Executes IE
}
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
return driver;
}
public WebDriver verifyPage() {
driver.get(url);
String Expected = driver.findElement(By.cssSelector("p[class='login-box-msg']")).getText();
String Actual = "Sign in to start your session";
Assert.assertEquals(Actual, Expected);
System.out.println("Homepage is displayed");
return driver;
}
}
Page Object class
I am getting NPE in user() method in this line return driver.findElement(username);
package pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPage {
public WebDriver driver;
By username = By.xpath("//input[#type='text']");
By password = By.xpath("//input[#type='password']");
By login = By.xpath("//button[#type='submit']");
By profile = By.xpath("//li[contains(#class,'nav-item dropdown user-menu')]/a[1]/img");
By logout = By.xpath("//li[#class='user-footer']/a[1]");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public WebElement user() {
return driver.findElement(username);
}
public WebElement pass() {
return driver.findElement(password);
}
public WebElement signIn() {
return driver.findElement(login);
}
public WebElement pro() {
return driver.findElement(profile);
}
public WebElement signOut() {
return driver.findElement(logout);
}
}
Testcase
When I run testcase when I call lp.user() geeting NPE error in page object class
package Admission;
import java.io.IOException;
import java.time.Duration;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import pageObjects.LoginPage;
import resources.base;
public class homePage extends base{
public WebDriver driver;
LoginPage lp = new LoginPage(driver);
#Test
public void loginDetails() throws IOException, InterruptedException
{
driver=initializeDriver();
verifyPage();
WebElement aadharNo = lp.user();
aadharNo.sendKeys("111111111111");
WebElement password = lp.pass();
password.sendKeys("21102021");
WebElement submit = lp.signIn();
submit.click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOf(lp.pro())).click();
WebDriverWait wait1 = new WebDriverWait(driver, Duration.ofSeconds(10));
wait1.until(ExpectedConditions.visibilityOf(lp.signOut())).click();
}
#Test
public void testCase() {
WebElement aadharNo = lp.user();
WebDriverWait wait2 = new WebDriverWait(driver, Duration.ofSeconds(30));
wait2.until(ExpectedConditions.visibilityOf(aadharNo));
aadharNo.sendKeys("111111111111");
WebElement password = lp.pass();
WebDriverWait wait3 = new WebDriverWait(driver, Duration.ofSeconds(20));
wait3.until(ExpectedConditions.elementToBeSelected(password));
password.sendKeys("hgfhg");
lp.signIn();
}
}
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)" because "this.driver" is null
at pageObjects.LoginPage.user(LoginPage.java:31)
at Admission.homePage.testCase(homePage.java:52)
You need to initializeDriver() before creating LoginPage object:
public class homePage extends base{
public WebDriver driver = initializeDriver();
LoginPage lp = new LoginPage(driver);
#Test
public void loginDetails() throws IOException, InterruptedException {
verifyPage();
WebElement aadharNo = lp.user();
aadharNo.sendKeys("111111111111");
WebElement password = lp.pass();
password.sendKeys("21102021");
WebElement submit = lp.signIn();
submit.click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOf(lp.pro())).click();
WebDriverWait wait1 = new WebDriverWait(driver, Duration.ofSeconds(10));
wait1.until(ExpectedConditions.visibilityOf(lp.signOut())).click();
}
(...)
}

Selenium Java - java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property

My FireFox Version 49.0.1
Selenium Version: Selenium-java-3.0.0-beta3
Java: 8.0.1010.13
I have replaced all the existing Selenium Jar Files with the new files. Added the gecko.Driver to my code still I am seeing this message:
Error Message:
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property;
My Code:
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AbstractPage {
WebDriver Driver =new FirefoxDriver();
#Before
public void Homescreen() throws InterruptedException
{
System.getProperty("Webdriver.gecko.driver", "C:/geckodriver.exe");
System.setProperty("Webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Driver.get("URL");
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#After
public void TestComplete() {
Driver.close();
}
#Test
public void Projects() {
Driver.findElement(By.id("login-form-username")).sendKeys("Login");
Driver.findElement(By.id("login-form-password")).sendKeys("Password");
Driver.findElement(By.id("quickSearchInput")).sendKeys("ID");
}
}
You can remove main() method from the code. unzip your gecko driver and save it to your local system with wires.exe.
my sample class path is
G:\ravik\Ravi-Training\Selenium\Marionette for firefox\wires.exe
public class AbstractPage
{
WebDriver Driver;
System.setProperty("WebDriver.gecko.Driver", "C:\\TEMP\\Temp1_geckodriver-v0.10.0-win64.zip");
Driver=new FirefoxDriver();
#Before
public void Homescreen() throws InterruptedException
{
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Driver.get("https://QualityAssurance.com");
Driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Driver.findElement(By.id("login-form-username")).sendKeys("Login");
Driver.findElement(By.id("login-form-password")).sendKeys("Password");
//JavascriptExecutor js = (JavascriptExecutor) Driver;
//js.executeScript("document.getElementById('login-form-password').setAttribute('value', val );");
}
#After
public void TestComplete() {
Driver.close();
}
#Test
public void Projects() {
Driver.findElement(By.id("quickSearchInput")).sendKeys("WMSSE-229");
Please replace below line
System.setProperty("WebDriver.gecko.Driver", C:\\TEMP\\Temp1_geckodriver-v0.10.0-win64.zip");
You should pass geckodriver.exe not Zip file.
String driverPath = "F:/Sample/Selenium3Example/Resources/";
System.setProperty("webdriver.firefox.marionette", driverPath+"geckodriver.exe");
You can make your code more cleaner when posting here.
You must do something like this:
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
This is a working example, it make you know the context what the above code snippet used
package selenium;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Junit4FirefoxJava {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.gecko.driver", "C:/geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "C:/Program Files (x86)/Mozilla Firefox/firefox.exe");
driver = new FirefoxDriver();
baseUrl = "http://www.bing.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testJunit4IeJava() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("sb_form_q")).click();
driver.findElement(By.id("sb_form_q")).clear();
driver.findElement(By.id("sb_form_q")).sendKeys("NTT data");
driver.findElement(By.id("sb_form_go")).click();
driver.findElement(By.linkText("NTT DATA - Official Site")).click();
driver.findElement(By.id("js-arealanguage-trigger")).click();
driver.findElement(By.linkText("Vietnam - English")).click();
driver.findElement(By.id("MF_form_phrase")).clear();
driver.findElement(By.id("MF_form_phrase")).sendKeys("internet");
driver.findElement(By.cssSelector("input.search-button")).click();
}
#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;
}
}
}

Selenium Webdriver pdf file signature location

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;
}
}
}

Selenium WebDriver NullPointerException while grabbing url

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!

Categories