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();
Related
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class HomePage {
WebDriver driver;
public HomePage() {
System.setProperty ("webdriver.chrome.driver", "D:\\Desktop\\Selenium\\chromedriver.exe");
this.driver = new ChromeDriver ();
PageFactory.initElements (driver, this);
}
#FindBy(xpath = "//*[#id='MenuContent']/a[2]")
WebElement signInButton;
public void signInButtonClick() {
signInButton.click();
}
}
and this is the main method:
import Pages.HomePage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
System.setProperty ("webdriver.chrome.driver", "D:\\Desktop\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver ();
driver.manage ().timeouts ().implicitlyWait (10, TimeUnit.SECONDS);
driver.manage ().window ().maximize ();
driver.get ("https://petstore.octoperf.com/actions/Catalog.action");
HomePage homePage = new HomePage ();
homePage.signInButtonClick ();
}
}
i am trying to get a locator (CSS or XPATH or really anything by this point) for a specific link and i cant manage no matter what I try.
this is the link in question:
Sign In
I have tried to find locators for a[text()='Sign In']
after I run the main method the process does not execute and this are the errors:
*** Element info: {Using=xpath, value=//*[#id='MenuContent']/a[2]}
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:78)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at jdk.proxy2/jdk.proxy2.$Proxy4.click(Unknown Source)
at Pages.HomePage.signInButtonClick(HomePage.java:23)
at Main.main(Main.java:17)
There are few things incorrect here.
Driver is getting initialized 2 times which should not be correct.
Path to geckodriver seems incorrect as well.
I am adding the correct code below but have used chromedriver instead of geckodriver. It is working with the below code.
package sample;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class HomePage {
WebDriver driver;
public HomePage() {
System.setProperty ("webdriver.chrome.driver", "/Users/riteshpc/Documents/eclipse-workspace/Drivers/chromedriver");
this.driver = new ChromeDriver();
PageFactory.initElements (driver, this);
}
#FindBy(xpath = "//a[text()='Sign In']")
WebElement signInButton;
public void signInButtonClick() {
signInButton.click();
}
}
package sample;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
public class Main {
public static void main(String[] args) {
HomePage homePage = new HomePage();
WebDriver driver = homePage.driver;
driver.manage().timeouts().implicitlyWait (10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://petstore.octoperf.com/actions/Catalog.action");
homePage.signInButtonClick();
}
}
To copy your driver location, you can simply go to the driver's folder location in your eclipse and right click the driver and from properties you can copy path.
I have added the screenshot below.
There are a few things that need to be corrected.
You are creating 2 drivers, one in main and one in HomePage. You should create driver from your main and pass that instance into HomePage through the constructor.
Your first XPath, as you posted it, is not valid. a[text()='Sign In'] should be //a[text()='Sign In'].
The creator of Selenium has stated that PageFactory and implicit waits are a bad practice and should not be used. Instead use the Page Object Model and WebDriverWait.
I rewritten your code and tested it and it successfully clicks the Sign In link.
Main.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import Pages.HomePage;
public class Main {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Desktop\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://petstore.octoperf.com/actions/Catalog.action");
HomePage homePage = new HomePage(driver);
homePage.signInButtonClick();
}
}
HomePage.java
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class HomePage {
WebDriver driver;
private By signInButton = By.xpath("//a[text()='Sign In']");
public HomePage(WebDriver driver) {
this.driver = driver;
}
public void signInButtonClick() {
driver.findElement(signInButton).click();
}
}
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
I'm having major issue trying to select menu two elements on a dropdown.I've tried xpaths, link texts and css selector but it wont select either the password button or logout button.
Xpaths used for Password button: "//*[#id='app']/header/div[3]/nav/ul/li/a"
CSS used for Logout button: ["data-logged-in-log-out-button"]
XPath used for Logout button: "//*[#id='app']/header/div[3]/nav/ul/a"
The error im getting for the select password is:
org.openqa.selenium.WebDriverException: unknown error: Element ... is not clickable at point (989, 233).
Other element would receive the click: ...
Please try with the below XPath along with the explicit wait condition.
XPath:
//*[contains(text(),'Log out')]
Can you please try -
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class A {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("url here");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log Out")));
driver.findElement(By.linkText("Log Out")).click();;
}
}
If it still doesn't work, please try -
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class A {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("url here");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", driver.findElement(By.linkText("Log Out")));
}
}
I am working on a Selenium testing framework tutorial of John Sonmez and ran into problem trying to perform the very first test. The test part consists of two methods: 1. LoginPage.GoTo(); which opens wordpress login page and 2. LoginPage.LoginAs("admin").Login(); which inserts username and clicks continue.
What happens when I run the test is wordpress loginpage opens and after 2 seconds blank Chrome browser opens and JUnit displays NoSuchElementException. The author of tutorial solved this problem adding some WebDriverWait and switchTo.ActiveElement.getAttribute() to LoginPage.GoTo(); method. However he is coding in C# and offers no solution for Java I'm coding in. I tried to apply WebDriverWait also but the problem is still there. Can anyone please suggest me how to solve this problem using WebDriverWait in Java.
LoginTest
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
import wordpressAutomation.Driver;
import wordpressAutomation.LoginPage;
public class LoginTest extends Driver {
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
LoginPage.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
}
LoginPage
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public static LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}
public class LoginCommand extends Driver {
private String username;
private String password;
public LoginCommand(String username) {
this.username = username;
}
public LoginCommand WithPassword(String password) {
this.password = password;
return this;
}
public void Login() {
WebElement login = openBrowser().findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
openBrowser().findElement(By.xpath("//button[#type = 'submit']")).click();
}
}
public class Driver {
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\KatarinaOleg\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
After opening the page, where you get the NoSuchElementException you can add in something like this.
FluentWait<WebDriver> webDriverWait = new WebDriverWait(driver, 25).pollingEvery(5, TimeUnit.SECONDS);
webDriverWait.until(ExpectedConditions.visibilityOf(webElement));
Just add in whatever element you want to use as your check to make sure the page has loaded
you have called the Openbrowser multiple times in Login Method from LoginCommand Class.So, It will be unnecessarily create different driver instance. So, your code needs to be modified as below along with explicit wait (Driver Class also needs to be changed as below)
Login Method from LoginCommand Class:
public void Login() {
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='usernameOrEmail']")));
WebElement login = driver.findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
driver.findElement(By.xpath("//button[#type = 'submit']")).click();
}
Driver Class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Driver {
WebDriver driver;
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
Edit: (dmin_user_can_login() method in LoginTest class)
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
l.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
LoginPage Class:
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}
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);