I am using selenium page factory. And while using any of the WebElements, I am receiving null pointer exception.
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.PagesUsingPageFactory.AddNewCustomerUsingPF;
import com.PageswithoutPageFactory.HomePage;
import com.PageswithoutPageFactory.InvokeBrowserSettings;
import com.PageswithoutPageFactory.LoginPage;
public class CreateNewCustomerNegative {
WebDriver driver;
#Test
public void TC_02() throws Exception{
HomePage hompg = new HomePage(driver);
AddNewCustomerUsingPF newcust = new AddNewCustomerUsingPF(driver);
LoginPage loginpage = new LoginPage(driver);
System.setProperty("webdriver.chrome.driver","C:\\Users\\Chinmay\\Downloads\\chromedriver_win32\\chromedriver.exe");
InvokeBrowserSettings invoke = new InvokeBrowserSettings();
driver = invoke.invokeBrowser("chrome", Constant.URL);
loginpage.SignIntoAppWithValidUsrPwd(driver);
//verify home page displayed after valid credentials
hompg.validateHomePageLogo(driver);
hompg.validateManagerButton(driver);
hompg.validatenewCustomerButton(driver);
hompg.clickNewCustomer(driver);
//driver.findElement(By.xpath("//a[contains(text(),'New Customer')]")).click();
//check if add new customer tab is present
Assert.assertTrue(driver.findElement(By.xpath("//p[contains(text(),'Add New Customer')]")).isDisplayed(), "Add new customer option is not visible");
//check if customer name textbox is present
Assert.assertTrue(driver.findElement(By.name("name")).isDisplayed(), "Customer name text box is not presernt");
//name field blank validation
System.out.println("driver=" + driver);
newcust.typeCustomerName("");
}
}
`
Whenever I am using pagefactory for identifying objects, it throws nullpointer exception.
The weird thing is the page factory works for first java file test case, when I use same page factory in another java file, it always fails with nullpointer exception.
I saw some solution on stackoverflow Selenium java.lang.NullPointerException with PageFactory
However, it did not work for me.
I tried initializing page object in my test case and also in my page object script. However, neither of it worked for me.
Here is the code for page factory :
package com.PagesUsingPageFactory;
import org.apache.commons.lang3.RandomStringUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class AddNewCustomerUsingPF {
public WebDriver driver;
public AddNewCustomerUsingPF(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy(how=How.XPATH, using="//p[contains(text(),'Add New Customer')]")
public WebElement addNewCustomerLabel;
#FindBy(how=How.XPATH, using="//input[#type='text'][#name='name']")
public WebElement customerNameTxtField;
#FindBy(how=How.XPATH, using="//a[contains(text(),'New Customer')]")
public WebElement newCustomerButton;
public void typeCustomerName(String name) throws Exception {
customerNameTxtField.sendKeys(name);
}
}
Please help me out. I am debigging this issue since more than a week and not able to find the solution.
see here
WebDriver driver;
#Test
public void TC_02() throws Exception{
HomePage hompg = new HomePage(driver);
i hope in HomePage, there is code to initialize driver, that why it is working. then you are passing driver which is not initialized
WebDriver driver;
So, you may need to try to collect driver from Homepage and then pass to other pages also.
As murail said, the driver is not initialized when page factory is intialized. It is passing driver as null.
Change page factory initialization after driver initialization as given below.
public class CreateNewCustomerNegative {
WebDriver driver;
#Test
public void TC_02() throws Exception{
//Initialize the driver first
System.setProperty("webdriver.chrome.driver","C:\\Users\\Chinmay\\Downloads\\chromedriver_win32\\chromedriver.exe");
InvokeBrowserSettings invoke = new InvokeBrowserSettings();
driver = invoke.invokeBrowser("chrome", Constant.URL);
//Initialize page factory
HomePage hompg = new HomePage(driver);
AddNewCustomerUsingPF newcust = new AddNewCustomerUsingPF(driver);
LoginPage loginpage = new LoginPage(driver);
loginpage.SignIntoAppWithValidUsrPwd(driver);
Related
I have a test in Selenium WebDriver with Page Object Model, if I run the following test open two windows in the Chrome browser, first window is empty in a URL line. How I can opening only one with onet.pl URL?
I trying deleting initialize Chrome driver but will have null.exception error.
What am I doing wrong?
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
private WebDriver driver;
//private WebDriverWait wait;
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
#FindBy(xpath="//div[#class='col-md-12']//form")
private WebElement loginForm;
#FindBy(id="username")
private WebElement loginField;
#FindBy(id="password")
private WebElement passwordField;
#FindBy(xpath="//button[#class='btn btn-multisport-default btn-multisport-large btn-full-width login-button']")
private WebElement buttonLogin;
public void open() {
driver.get("https://onet.pl");
}
public void enterLogin() {
String login = "vadim1234#test.pl";
loginField.sendKeys(login);
}
public void enterPassword() {
String password = "Benefit!";
passwordField.sendKeys(password);
}
public void login() {
buttonLogin.click();
}
}
And test code:
import Pages.Dashboard;
import Pages.LoginPage;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
public class LogIn {
#Test
public void correctLogin() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
WebDriver driver = new ChromeDriver();
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
loginPage.open();
loginPage.enterLogin();
loginPage.enterPassword();
loginPage.login();
driver.close();
driver.quit();
Dashboard dashboard = new Dashboard(driver);
dashboard.getLoggedUser();
}
}
From your test class as you are passing the reference of the driver:
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
In LoginPage class, within the constructor, instead of:
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
you need to do reuse the instance passed as follows:
public LoginPage(WebDriver loginPageDriver) {
this.driver=loginPageDriver;
}
That would solve the issue of 2 browsers getting opened.
References
You can find a couple of relevant detailed discussions in:
Selenium [Java] PageFactory Design : Where do I write my Assertions following Page Object Model
Selenium newbie here... I am trying to create my first test framework .
Test Website : https://www.phptravels.net/
Test Case :
Open Browser and enter the webpage
Once the page is loaded , click on MyAccount ->Login
I have used xpath in my page object class and the script will run only till launching the webpage. It fails to click on the Login link .
I have tried to include an implicit wait assuming that the time taken for the page to load is longer than usual . Even then the issue persists.
Can you please help me understand what would be the correct xpath that this will work ?
Code :
POM_HomePage.java
package PageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class POM_HomePage {
WebDriver driver;
public POM_HomePage(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//*[#id='li_myaccount']/ul/li[1]/a")
WebElement LinkMyAccount;
public WebElement clickMyAccount() {
return LinkMyAccount;
}
}
HomePage.java
package TestGroupID;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
import PageObjects.POM_HomePage;
import Resources.MasterScript;
public class HomePage extends MasterScript{
#Test
public void SignIn() throws IOException {
driver=LoadBrowser();
LoadPropFile();
driver.get(prop.getProperty("test_website"));
POM_HomePage pomHome=new POM_HomePage(driver);
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
if (pomHome.clickMyAccount().isDisplayed()) {
pomHome.clickMyAccount().click();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
}
}
}
As per your question you have mentioned Once the page is loaded click on MyAccount ->Login. So you should have invoked click() method on two separate WebElements. But your POM_HomePage.java returns only one WebElement as #FindBy(xpath="//*[#id='li_myaccount']/ul/li[1]/a")
Solution
In POM_HomePage.java define two WebElements and two associated functions() as follows :
MyAccount Link
#FindBy(xpath="//div[#class='navbar']//li[#id='li_myaccount']/a")
WebElement LinkMyAccount;
public WebElement clickMyAccount() {
return LinkMyAccount;
}
Login Link
#FindBy(xpath="//div[#class='navbar']//li[#id='li_myaccount']//ul[#class='dropdown-menu']/li/a[contains(.,'Login')]")
WebElement LinkLogin;
public WebElement clickLogin() {
return LinkLogin;
}
In HomePage.java call isDisplayed() and click() for both the WebElements as follows :
#Test
public void SignIn() throws IOException {
driver=LoadBrowser();
LoadPropFile();
driver.get(prop.getProperty("test_website"));
POM_HomePage pomHome=new POM_HomePage(driver);
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
if (pomHome.clickMyAccount().isDisplayed()) {
pomHome.clickMyAccount().click();
}
if (pomHome.clickLogin().isDisplayed()) {
pomHome.clickLogin().click();
}
}
" Here is the code of selenium web driver in which i use POM design to define all the locators of the web page. So after running the code i got an error regarding the null pointer exception.
"
{
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By username = By.id("user_login");
By password = By.id("user_pass");
By login = By.id("wp-submit");
By rememberme = By.id("rememberme");
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
public void typepassword(){
driver.findElement(password).sendKeys("demo123");
}
public void clickrememberme(){
driver.findElement(rememberme).click();
}
public void clicklogin(){
driver.findElement(login).click();
}
}
"Here in this code i created an object of a login page and call all the locators using TestNG annotations."
{
package Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
public class verifylogin {
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
WebDriver driver = null;
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
}
You might want to consider studying scope in java to understand what is happening in this issue. Here is an explanation for what is happening in your case.
In your public void beforetest() method, you're creating a driver, and using it, but when that method is done the driver variable goes out of scope, and you no longer have access to it.
Later, in your verifyValidLogin method, you're creating a new driver variable, and setting it to null:
WebDriver driver = null;
Then you pass this null driver to your LoginPage here:
LoginPage login_test = new LoginPage(driver);//driver is null here
So when you use it here:
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
It's null
Try making these changes:
First, save your driver somewhere when you initialize it like this:
public class verifylogin {
//STORE YOUR DRIVER SOMEWHERE!!! Like here
private WebDriver driver;
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\chrome\\chromedriver.exe");
//Store the driver in the class variable
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
//Now you can use the driver you stored
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
You are removing object reference by using "WebDriver driver = null" in verifyvalidlogin() method. Remove this line and try, it will work.
You instance variable 'driver' as private ('private WebDriver driver').
With 'private' access modifier you can access driver within the class but not from outside, change it to public it will work.
In beforetest() method you are instantiating the browser object and navigating to demo Url.
After that in verifyvalidlogin() method you are making driver object to null and passing this null object to Login page, here you are passing null instead of driver object.
We can solve this issue by declaring driver instance variable inside the class and outside of all methods like below.
WebDriver driver;
Instantiate this driver object in beforetest() method and pass the same driver object to LoginPage without declaring it again as mentioned below.(I executed this script in my local machine its working fine)
package Tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
public class verifylogin {
WebDriver driver;
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\ chrome\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
}
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By username = By.id("user_login");
By password = By.id("user_pass");
By login = By.id("wp-submit");
By rememberme = By.id("rememberme");
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
public void typepassword(){
driver.findElement(password).sendKeys("demo123");
}
public void clickrememberme(){
driver.findElement(rememberme).click();
}
public void clicklogin(){
driver.findElement(login).click();
}
}
Try this solution and let me know if it works for you.
I have a question related to improving my Selenium Java code. I am really beginner in Java and Selenium either.
I have written a code which I got an example from the internet and adapted to my reality. The coding works fine as described below:
package test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import page.Login;
public class LoginTest extends BaseTest {
Login login = new Login(driver);
#Test
public void loginWithSuccess() {
sendLoginData("my_user#something.com", "my_password");
login.clickLogin();
assertEquals("View Posted Jobs", login.checkLoginSuccess());
}
private void sendLoginData(String user, String password) {
login.sendUser(user);
login.sendPassword(password);
}
}
The above program is testing and performing a loginWithSucess in the WebSite
package config;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebDriverFactory {
public static WebDriver createFirefoxDriver() {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
In this above example I am instancing a new object WebDriver called driver.
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import config.WebDriverFactory;
public class BaseTest {
protected static WebDriver driver;
private static boolean setUpIsDone = false;
#BeforeClass
public static void setUp() {
if (setUpIsDone) {
return;
}
// Creating first browser for student login
driver = WebDriverFactory.createFirefoxDriver();
driver.get("http://test-tuitiondesk.rhcloud.com/auth");
driver.manage().window().maximize();
setUpIsDone = true;
}
The above example is where I open my WebSite to authenticate
package page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Login {
private WebDriver driver;
public Login(WebDriver driver) {
this.driver = driver;
}
public void sendUser(String user) {
driver.findElement(By.xpath("//*[#id='email']")).sendKeys(user);
}
public void sendPassword(String password) {
driver.findElement(By.id("password")).sendKeys(password);
}
public void clickLogin() {
driver.findElement(By.xpath("//*[#id='login-box']/div/div[1]/form/fieldset/div[2]/button")).click();
}
public String checkLoginSuccess() {
return driver.findElement(By.xpath("//a[contains(text(),'View Posted Jobs')]")).getText();
}
}
The above example I have methods which will send a user id and password to the webpage.
So far is everything working fine. The program is performing the following steps:
1 - Open the firefox
2 - Open the webpage
3 - Send the correct user_id, password and click in login button
4 - Check if login was performed with success.
My question now is that I need open a new firefox driver and login with different user_id and this new user_id will interact some actions with the first user_id, so I will need two browsers opened to perform actions with both users in the same time.
I would like to write this implementation the best way than simply write every method again with the second driver. What I thought for the first time was create a new WebDriver called driver2 and create again all methods referring to driver2, but I think I should reuse my methods and classes in a clever way.
Does Anybody have any idea how to implement this second browser in my code?
Thank you
André
You can do this simply by entering this code:
driver2 = WebDriverFactory.createFirefoxDriver();
driver2.get("http://test-tuitiondesk.rhcloud.com/auth");
//call log in function for driver2
//code to interact driver2 with driver1
Using an example from Selenium Wedriver Practical Guide (to login in and create a test post on Wordpress), I encounter the above mentioned error.
Here is the PageObject that I am using:
package com.PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
/**
* Created by JTester on 3/9/2016.
*/
public class AdminLoginPage {
WebDriver driver;
#FindBy(how=How.ID, id="user_login")
WebElement email;
#FindBy(how=How.ID, id="user_pass")
WebElement pwd;
#FindBy(how=How.ID, id="wp-submit")
WebElement submit;
public AdminLoginPage(WebDriver driver){
this.driver = driver;
driver.get("http://mysite.wordpress.com/wp-admin/");
}
public void login(){
email.sendKeys("myEmailAddress#yahoo.com");
pwd.sendKeys("myPasswd");
submit.click();
}
}
And here is the test class:
package com.features.trial;
import com.PageObjects.AdminLoginPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
* Created by JTester on 3/9/2016.
*/
public class TestAddNewPost {
public static void main(String... args) {
WebDriver driver = new FirefoxDriver();
//login to wordpress admin
AdminLoginPage admLoginPage = new AdminLoginPage(driver);
admLoginPage.login();
//go to AllPosts page
driver.get("http://mysite.wordpress.com/wp-admin/edit.php");
//add a new post
WebElement addNewPost = driver.findElement(By.linkText("Add New"));
addNewPost.click();
//add new post's content
driver.switchTo().frame("content_ifr");
WebElement postBody = driver.findElement(By.id("tinymce"));
postBody.sendKeys("This is my description.");
driver.switchTo().defaultContent();
WebElement title = driver.findElement(By.id("title"));
title.sendKeys("This is my first post");
//publish my post
WebElement publish = driver.findElement(By.id("publish"));
publish.click();
}
}
Since I am new to Selenium and Page Objects, could anyone explain why it is throwing the following error:
Exception in thread "main" java.lang.NullPointerException
at com.PageObjects.AdminLoginPage.login(AdminLoginPage.java:29)
at com.features.trial.TestAddNewPost.main(TestAddNewPost.java:17)
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:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Process finished with exit code 1
Many thanks..
ps: After looking at a lot of code examples on the web, I think I need to use PageFactory to instantiate my elements but not sure if this is true, and if it is, how do I go about it using my example code.
Debugger Screenshot :
AdminLoginPage should have been initialized using PageFactory.
import org.openqa.selenium.support.PageFactory;
public AdminLoginPage(WebDriver driver){
PageFactory.initElements(driver, this); //add this
this.driver = driver;
driver.get("http://mysite.wordpress.com/wp-admin/");
}
Add the following code:
AdminLoginPage loginPage = PageFactory.initElements(driver,AdminLoginPage.class);
loginPage.login();
to the TestAddNewPost class, instead of using the existing code:
AdminLoginPage admLoginPage = new AdminLoginPage(driver);
admLoginPage.login();