Page Object Factory - NullPointerException - java

Using Page Object Model and Page Factoring for the login page, where I get the objects in the LoginPage.java and the actions are in the LoginScript.java.
I get a java.lang.NullPointerException in the line "Ele_UserNameEdit.clear();" please help to check the code. Thanks.
This is my Loginpage.java :
package com.cos.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
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 org.testng.Assert;
public class loginpage {
public String Logout_Xpath = "//nav[#class=\"menu_right ng-tns-c1-0 ng-star-inserted\"]/a[3]/div/img";
#FindBy(id = "email_input")
WebElement Ele_UserNameEdit;
#FindBy(id = "email_input")
WebElement USERNAME_ELE;
#FindBy(id="password_input")
WebElement Ele_PasswordEdit;
#FindBy(xpath = ".//*[#class='theme_button blue log_in_btn']")
WebElement Ele_LoginButton;
#FindBy(xpath = "html/body/ngb-modal-window/div/div/selectcountry/div/div/div[1]/div/div[1]/div/div/i")
WebElement Ele_ThailandRadioButton;
#FindBy(xpath = "//div[#class=\"theme_button blue pointer\"]")
WebElement Ele_ExploreThePortalButton;
#FindBy(xpath = "//div[#class=\"theme_button blue logout_btn\"]")
WebElement Ele_LogoutConfirmationButton;
public void HomePage(WebDriver driver){
PageFactory.initElements(driver, this);
}
public void enterUserName(String UserName){
Ele_UserNameEdit.clear();
Ele_UserNameEdit.sendKeys(UserName);
}
public void enterPassword(String Password){
Ele_PasswordEdit.clear();
Ele_PasswordEdit.sendKeys(Password);
}
public void clickOnLogin(WebDriver driver){
try {
WebDriverWait wait = new WebDriverWait(driver, 20);
Ele_LoginButton.click();
Thread.sleep(4000);
Ele_ThailandRadioButton.click();
Thread.sleep(4000);
Ele_ExploreThePortalButton.click();
Thread.sleep(4000);
WebElement coslogoutLink;
coslogoutLink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Logout_Xpath)));
Assert.assertTrue(coslogoutLink.isDisplayed());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clickOnLogout(WebDriver driver) {
//Logout
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement coslogoutLink;
coslogoutLink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(Logout_Xpath)));
Assert.assertTrue(coslogoutLink.isDisplayed());
coslogoutLink.click();
Ele_LogoutConfirmationButton.click();
// close Fire fox
driver.close();
}
}
This is my LoginScript.java :
package com.cos.test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.cos.actions.LoginActions;
import excel.ReadDataFromExcel;
public class LoginScript extends BaseClass {
#Test(dataProvider = "readFromExcel")
public void testLogin(String userName, String password) {
LoginActions actions = new LoginActions();
actions.login(driver, userName, password);
actions.logout(driver);
}
#DataProvider(name = "readFromExcel")
public Object[][] readDataFromExcel() throws Exception {
Object[][] dataFromExcel = ReadDataFromExcel.readDataFromExcel();
return dataFromExcel;
}
}

First of all You have duplicated #FindBy(id = "email_input").
public class loginpage should have constructor when initialization is called with new loginpage();
PageFactory.initElements(driver, this);
so when You do loginpage login = new loginpage(); it doesn't initialize Your PageFactory, because You've made it an method not constructor.
So try like this
public LoginPage(WebDriver webDriver) {
super(webDriver); //this is if You extend driver from super-class
PageFactory.initElements(webDriver, this);
}
But just add code into constructor under pagelogin class.
Hope this is helpful.

Related

How do I click on this autoComplete countryName?

This is the link I wanted to automate. But I am not being able to click on countryName. I wanted to enter "na" in the searchField and then click on "Nepal" using the list attribute i.e list.get(i).click() but I have not been able to. Please help
package autoComplete;
import java.time.Duration;
import java.util.List;
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.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//input[#type='hidden']");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
List<WebElement> listOfCountry = driver.findElements(countryList);
// driver.findElement(nepalClick).click();
for (int i = 0; i < listOfCountry.size(); i++) {
// System.out.println(list);
String searchText = listOfCountry.get(i).getAttribute("value");
System.out.println(searchText);
if (searchText.equals("Nepal")) {
listOfCountry.get(i).click();
}
}
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
}
This is the error screenshot:
Error Screenshot
You needn't iterate through the whole list if you just want to click the "Nepal" option. Does the following help at all?
driver.findElement(By.CSS_SELECTOR, 'input[value="Nepal"]').click()
you can use Webdriver wait with a customExpected Condition like this below
Instead of using implicit wait use WebDriverwait for Fluentwait
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return ( driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
Also modified below locator like this, as you will get element not clickable exception on using that
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
Full code below which is working for me
import io.github.bonigarcia.wdm.WebDriverManager;
import java.time.Duration;
import java.util.List;
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.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));
wait.until(waitForDropdownElement(countryList, "Nepal"));
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return (driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
}

java.lang.NullPointerException exception is occurred when running the test script Page Object Model using Selenium Web Driver

package com.qa.base;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.qa.util.TestUitl;
public class TestBase {
public static WebDriver driver;
public static Properties prop;
// Creating a Constructor
public TestBase() {
prop = new Properties();
try {
File file = new File("/APIAutomation/CRMTest/src/main/java/com/qa/config/config.properties");
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void initializtion() {
String browser = prop.getProperty("browser");
if(browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:/APIAutomation/chromedriver.exe");
driver = new ChromeDriver();
}
else
{
System.out.println("Quit Running Script");
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(TestUitl.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUitl.IMPLICIT_WAIT, TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
}
Page Factory
package com.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.base.TestBase;
public class loginPage extends TestBase{
//Page Factory
#FindBy(name="email")
WebElement email;
#FindBy(name="password")
WebElement password;
#FindBy(xpath=".//div[#class='ui fluid large blue submit button']")
WebElement loginButton;
#FindBy(xpath="//div[#class ='column']/div[2][#class='ui message']")
WebElement OldLogin;
//Initialization the Page Object
public loginPage() {
PageFactory.initElements(driver, this);
}
//Actions
public String validateLoginPageTitle() {
return driver.getTitle();
}
public String validateUserName() {
return OldLogin.getText();
}
public HomePage login(String user, String pass) {
email.sendKeys(user);
password.sendKeys(pass);
loginButton.click();
return new HomePage();
}
}
Page Factory HomePage
package com.qa.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.base.TestBase;
public class HomePage extends TestBase{
//PageFactory
#FindBy(xpath = ".//div[#id='main-nav']/a[#href='/home']")
WebElement Homepage;
#FindBy(xpath =".//div/span[#class='user-display']")
WebElement username;
#FindBy(xpath =".//span[contains(text(),'Contacts')]")
WebElement contactlink;
#FindBy(xpath="//a[5][contains(#href,'/deals')]")
WebElement dealslink;
//Initializing Page Object
public HomePage() {
PageFactory.initElements(driver, this);
}
//Actions
public String validateHomePage() {
return driver.getTitle();
}
public boolean validateHomePageDisplayed() {
return Homepage.isDisplayed();
}
public String validateUser() {
return username.getText();
}
public boolean verifyUsername() {
return username.isDisplayed();
}
public ContactPage clickContactLink() {
contactlink.click();
return new ContactPage();
}
public DealsPage clickDeals() {
dealslink.click();
return new DealsPage();
}
}
Test Case Class
package com.crm.qa.TestCases;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.base.TestBase;
import com.qa.pages.ContactPage;
import com.qa.pages.HomePage;
import com.qa.pages.loginPage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class HomePageTest extends TestBase {
loginPage loginpage;
HomePage homepage;
ContactPage contactpage;
//Create a constructor of HomePageTest and call the super class i.e the TestBase class constructor will be called
public HomePageTest() {
super();
}
// test case should be separated - independent with each other
// before each test cases - launch the browser and login
// after each test cases - close the browser
#BeforeMethod
public void setUp() {
initializtion();
loginpage = new loginPage();
//Login method is returning homepage object
homepage = loginpage.login(prop.getProperty("username"), prop.getProperty("password"));
}
#Test
public void verifyHomePageTitleTest() {
String homepageTitle = homepage.validateHomePage();
System.out.println("Print HomePage Title:::::::::::::::::" +homepageTitle);
Assert.assertEquals(homepageTitle, "Cogmento CRM","Homepage title is not matching");
}
#Test
public void verifyUsernameTest() {
Assert.assertTrue(homepage.verifyUsername(), "Username is not matching");
}
#Test
public void verifyUserTest() {
String Username = homepage.validateUser();
Assert.assertEquals(Username, "Gokul Kuppusamy","Username text is not matching");
}
#Test
public void verifyContactPageTest() {
System.out.println("Clicking Contact Page");
contactpage = homepage.clickContactLink();
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
package com.crm.qa.TestCases;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.base.TestBase;
import com.qa.pages.ContactPage;
import com.qa.pages.HomePage;
import com.qa.pages.loginPage;
public class ContactPageTest extends TestBase {
loginPage loginpage;
HomePage homepage;
ContactPage contactpage;
public ContactPageTest() {
super();
}
#BeforeMethod
public void setUp() throws Exception {
initializtion();
loginpage = new loginPage();
// Login method is returning homepage object
homepage = loginpage.login(prop.getProperty("username"), prop.getProperty("password"));
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
Thread.sleep(3000);
homepage.validateHomePageDisplayed();
/*
* Thread.sleep(3000); homepage.clickContactLink(null);
*/
}
#Test
public void verifyContactsPageNewButtonTest() {
Assert.assertTrue(contactpage.verifyNewButton());
}
#Test(priority = 1)
public void verifyContactsPageLableTest() {
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
Assert.assertTrue(contactpage.verifyContactlable(), "Contacts is missing on the page");
}
#Test(priority = 2)
public void selectContactDetailsTest() {
contactpage.selectContactDetails();
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
java.lang.NullPointerException
at com.crm.qa.TestCases.ContactPageTest.verifyContactsPageNewButtonTest(ContactPageTest.java:49)
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)
initializtion();
loginpage = new loginPage();
//below line is missing please add in HomePageTest class
**homepage=new Homepage();**
Please confirm whether you are using only one driver instance for all pages, Basically Null point exception occurring for this , The solution uses a global variable for driver instance
public static Webdrivr driver;

Can you tell me where i did mistake

package hrmInfoModule;
import java.util.concurrent.TimeUnit;
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.interactions.Actions; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
public class Hrmlogin {
public WebDriver driver;
#BeforeTest
public void openbrowser()
{
System.setProperty("webdriver.chrome.driver", "D:\\Software\\chromedriver.exe");
driver = new ChromeDriver ();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
#Test
public void login() throws InterruptedException
{
String Url="https://opensource-demo.orangehrmlive.com/";
String ID ="Admin";
String Pswrd="admin123";
driver.get(Url);
WebElement login = driver.findElement(By.id("txtUsername"));
login.sendKeys(ID);
WebElement paswrd = driver.findElement(By.id("txtPassword"));
paswrd.sendKeys(Pswrd);
WebElement btn = driver.findElement(By.id("btnLogin"));
btn.click();
Thread.sleep(2000);
}
#Test
public WebElement Admin() throws InterruptedException
{
Thread.sleep(2000);
WebElement Admin = driver.findElement(By.xpath(("//*[#id='menu_admin_viewAdminModule']")));
return Admin;
}
#Test
public WebElement JobTitle(WebElement Admin) throws InterruptedException
{
Thread.sleep(2000);
WebElement job = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/a"));
WebElement jobtitles = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/ul/li[1]/a"));
Actions act= new Actions(driver);
Thread.sleep(2000);
act.moveToElement(Admin).moveToElement(job).moveToElement(jobtitles).click().build().perform();
WebElement AddBtn= driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddBtn.click();
driver.findElement(By.xpath(("//*[#id='jobTitle_jobTitle']"))).sendKeys("Manager");
driver.findElement(By.xpath(("//*[#id='jobTitle_jobDescription']"))).sendKeys("zxc");
driver.findElement(By.xpath(("//*[#id='jobTitle_note']"))).sendKeys("jobTitle_note");
WebElement SaveBtn= driver.findElement(By.xpath(("//input[#value='Save']")));
Thread.sleep(2000);
SaveBtn.click();
return job;
}
#Test
public void PayGrade(WebElement job) throws InterruptedException
{
//WebElement job = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/a"));
WebElement payGrade = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/ul/li[2]/a"));
Actions act= new Actions(driver);
act.moveToElement(job).moveToElement(payGrade).click().build().perform();
WebElement AddPayBtn= driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddPayBtn.click();
driver.findElement(By.xpath(("//*[#id='payGrade_name']"))).sendKeys("INR");
WebElement SavePayBtn= driver.findElement(By.xpath(("//input[#value='Save']")));
Thread.sleep(2000);
SavePayBtn.click();
}
#AfterTest
public void teardown()
{
driver.quit();
} }
In above code TestNG passing only one Test named as Login(). Can anyone tell me please why is it so?
How to improve this code and run all tests in a series.
When I run your code, I get the following log:
PASSED: login
FAILED: PayGrade
org.testng.TestNGException:
Cannot inject #Test annotated Method [PayGrade] with [interface org.openqa.selenium.WebElement].
For more information on native dependency injection please refer to https://testng.org/doc/documentation-main.html#native-dependency-injection
I do not think put WebElement job as parameter of PayGrade(WebElement job) is right, so try to fix this kind of codes.
EDIT 1:
Details in code comments:
package hrmInfoModule;
import java.util.concurrent.TimeUnit;
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.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Hrmlogin {
public WebDriver driver;
/*
* put common xpath string here
*/
String xJob = "//a[#id='menu_admin_Job']";
String xJobTitles = "//a[#id='menu_admin_viewJobTitleList']";
String xPayGrade = "//a[#id='menu_admin_viewPayGrades']";
#BeforeTest
public void openbrowser() {
System.setProperty("webdriver.chrome.driver", "D:\\Software\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
#Test (priority = 0)
public void testLogin() throws InterruptedException {
String Url = "https://opensource-demo.orangehrmlive.com/";
String ID = "Admin";
String Pswrd = "admin123";
driver.get(Url);
WebElement login = driver.findElement(By.id("txtUsername"));
login.sendKeys(ID);
WebElement paswrd = driver.findElement(By.id("txtPassword"));
paswrd.sendKeys(Pswrd);
WebElement btn = driver.findElement(By.id("btnLogin"));
btn.click();
Thread.sleep(2000);
}
#Test (priority = 1)
public void testAdmin() throws InterruptedException {
WebElement admin = driver.findElement(By.xpath(("//*[#id='menu_admin_viewAdminModule']")));
/**
* Notice:
* 1. If there are no effective steps in this function, it should be removed.
* 2. click() is more stable than Actions.moveTo()
*/
admin.click();
Thread.sleep(2000);
}
#Test (priority = 2)
public void testJobTitle() throws InterruptedException {
Thread.sleep(2000);
WebElement job = driver.findElement(By.xpath(xJob));
WebElement jobTitles = driver.findElement(By.xpath(xJobTitles));
Actions act = new Actions(driver);
Thread.sleep(2000);
act.moveToElement(job).moveToElement(jobTitles).click().build().perform();
WebElement AddBtn = driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddBtn.click();
driver.findElement(By.xpath(("//*[#id='jobTitle_jobTitle']"))).sendKeys("Manager");
driver.findElement(By.xpath(("//*[#id='jobTitle_jobDescription']"))).sendKeys("zxc");
driver.findElement(By.xpath(("//*[#id='jobTitle_note']"))).sendKeys("jobTitle_note");
WebElement SaveBtn = driver.findElement(By.xpath(("//input[#value='Save']")));
SaveBtn.click();
Thread.sleep(2000);
}
#Test (priority = 3)
public void testPayGrade() throws InterruptedException {
WebElement job = driver.findElement(By.xpath(xJob));
WebElement payGrade = driver.findElement(By.xpath(xPayGrade));
Actions act = new Actions(driver);
act.moveToElement(job).moveToElement(payGrade).click().build().perform();
WebElement AddPayBtn = driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddPayBtn.click();
driver.findElement(By.xpath(("//*[#id='payGrade_name']"))).sendKeys("INR");
WebElement SavePayBtn = driver.findElement(By.xpath(("//input[#value='Save']")));
Thread.sleep(2000);
SavePayBtn.click();
}
#AfterTest
public void teardown() {
driver.quit();
}
}

Two firefox browser windows open in my selenium

I am using a firefox driver and I notice that because I initialize a new instance of the firefox Driver, I have two fireFox windows open when my test runs. Is there a correct way in terms of initialising the driver as I may be wrong but I am guessing I shouldn't be writing WebDriver webDriver = new FirefoxDriver(); in two locations and somehow write it within one location only and call on it?
Page 1:
public class waitMethods extends PageObject {
WebDriver webDriver = new FirefoxDriver();
public void waitForElementToBeDisplayed(By element){
try {
WebDriverWait webDriverWait = new WebDriverWait(webDriver, 30);
webDriverWait.until(ExpectedConditions.presenceOfElementLocated(element));
System.out.println(element + " is displayed correctly");
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
System.out.println(element + " is not displayed");
}
}
Page 2:
public class WebPageMethods extends PageObject {
WebDriver webDriver = new FirefoxDriver();
public void navigateToAuth0WebPage(){
webDriver.get("https://www.test.com");
}
There is an example, how to inherit from WebDriver:
WebDriver setup class:
package brucey;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class WebDriverSetup {
public static WebDriver driver;
public static String driverPath = "C:\\Users\\pburgr\\Desktop\\selenium-tests\\FF_driver_0_23\\geckodriver.exe";
public static WebDriver startFF() {
FirefoxOptions options = new FirefoxOptions();
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile selenium_profile = allProfiles.getProfile("selenium_profile");
options.setProfile(selenium_profile);
options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver", driverPath);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
return driver;
}
public static void shutdownFF() {
driver.quit();
}
}
Class containing methods used by driver:
package brucey;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class WebDriverBase extends WebDriverSetup {
#BeforeClass public static void setUpClass() {
startFF();
}
#Before public void setUp() {}
#After public void tearDown() {}
#AfterClass public static void tearDownClass() {
shutdownFF();
}
public WebDriverWait waitSec(WebDriver driver, int sec) {
return new WebDriverWait(driver, sec);
}
public WebElement byId(String id) {
WebElement element = driver.findElement(By.id(id));
return element;
}
public WebElement byXpath(String xpath) {
WebElement element = driver.findElement(By.xpath(xpath));
return element;
}
public WebElement byText(String text) {
WebElement element = driver.findElement(By.linkText(text));
return element;
}
public WebElement clickableByXpath(String xpath, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
return element;
}
public WebElement clickableByName(String name, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.elementToBeClickable(By.name(name)));
return element;
}
public WebElement visibleByXpath(String xpath, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return element;
}
public WebElement visibleById(String id, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
return element;
}
public List<WebElement> byXpaths(String xpath) {
List<WebElement> elements = driver.findElements(By.xpath(xpath));
return elements;
}
public void atr2beByXpath(int sec, String xpath, String atr, String val) {
waitSec(driver, sec).until(ExpectedConditions.attributeToBe(By.xpath(xpath), atr, val));
}
public void atrNot2beByXpath(int sec, String xpath, String atr, String val) {
waitSec(driver, sec).until(ExpectedConditions.not(ExpectedConditions.attributeToBe(By.xpath(xpath), atr, val)));
}
public void elements2beMoreByXpath(String xpath, int sec, int amount) {
waitSec(driver, sec).until(ExpectedConditions.numberOfElementsToBeMoreThan(By.xpath(xpath), amount));
}
public void elements2beByXpath(String xpath, int sec, int amount) {
waitSec(driver, sec).until(ExpectedConditions.numberOfElementsToBe(By.xpath(xpath), amount));
}
public void tryUrl2be(int sec, String url) {
try {waitSec(driver, sec).until(ExpectedConditions.urlToBe(url));
} catch (TimeoutException e) {}
}
public void tryUrl2contain(int sec, String string) {
try {waitSec(driver, sec).until(ExpectedConditions.urlContains(string));
} catch (TimeoutException e) {}
}
}
Test class:
package brucey;
import org.junit.Test;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class TestExample extends WebDriverBase {
#Test
public void testExample() {
driver.get("https://www.google.com");
waitSec(driver, 10).until(ExpectedConditions.elementToBeClickable(byId("some WebElement's ID")));
// ...
}
}

Selenium null pointer exception, when trying to use constructor

I created a class which has page objects defined in it. Then I am trying to use that class in a test class by using a constructor. However when I run the test class using JUnit I am getting a NullPointerException error.
Page_Objects Class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
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.support.ui.Select;
public class Page_Objects {
private WebDriver driver;
WebElement Username = driver.findElement(By.id("username"));
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
WebElement Password = driver.findElement(By.id("password"));
WebElement Login_Button = driver.findElement(By.id("Login"));
WebElement Logout_Button = driver.findElement(By.linkText("Logout"));
}
Test Class:
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.Select;
public class Salesforce_Test {
private WebDriver driver1;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
Page_Objects pageobjects = new Page_Objects();
#Before
public void setUp() throws Exception {
driver1 = new FirefoxDriver();
baseUrl = "some url for testing/";
driver1.navigate().to(baseUrl);
driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void Login_Logout() throws Exception {
pageobjects.Username.sendKeys("someusername");
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
pageobjects.Password.sendKeys("somepassword");
pageobjects.Login_Button.click();
pageobjects.Logout_Button.click();
}
#After
public void tearDown() throws Exception {
driver1.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver1.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver1.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver1.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
When I run the above class I get a null pointer exception.
java.lang.NullPointerException
at Page_Objects.<init>(Page_Objects.java:20)
at Salesforce_Test.<init>(Salesforce_Test.java:16)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
I see two issues here. First is that the Page_Objects class is called before you initiated the driver. That's why when you're calling
Page_Objects pageobjects = new Page_Objects();
you're getting a NullPointerException.
So you want to initiate the Page_Objects after you've initiated the driver.
Second, you need to pass it the instance of the driver you've initiated, because right now it has its own Private driver which isn't initiated and therefore it's null.
So in short:
Initiate Page_Objects after you've initiated driver (after the driver1 = new FirefoxDriver(); line)
Call it with the driver you've initiated: Page_Objects pageobjects = new Page_Objects(driver1 );

Categories

Resources