How to add explicit wait in PageFactory in PageObjectModel? - selenium

I have added hardcode wait thread.sleep() in my below code. How to use explicit wait. I want to wait till "username" WebElement appear. My program is working perfectly. I have already written testcases.
package com.pol.zoho.PageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(xpath=".//*[#id='lid']")
public WebElement email;
#FindBy(xpath=".//*[#id='pwd']")
public WebElement password;
#FindBy(xpath="//*[#id='signin_submit']")
public WebElement signin;
public void doLogin(String username,String userpassword)
{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
email.sendKeys(username);
password.sendKeys(userpassword);
signin.click();
}
}

When using PageFactory in PageObjectModel if you expect the element to be loaded through some JavaScript and it might not be present on the page already you can use the Explicit Wait support with a normal locator factory as follows:
Code Block:
package com.pol.zoho.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.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(xpath=".//*[#id='lid']")
public WebElement email;
#FindBy(xpath=".//*[#id='pwd']")
public WebElement password;
#FindBy(xpath="//*[#id='signin_submit']")
public WebElement signin;
public void doLogin(String username,String userpassword)
{
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
email.sendKeys(username);
password.sendKeys(userpassword);
signin.click();
}
public WebElement getWebElement()
{
return email;
}
}
You can find a detailed discussion in How to use explicit waits with PageFactory fields and the PageObject pattern

You have two options:
1- You can use implicity wait while initializing the driver.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
2- Use explicty wait for the username field only:
WebDriverWait wait = new WebDriverWait(driver,30);
WebElement element = wait.until(
ExpectedConditions.visibilityOf(By.id(identifier)));

Related

NUll Pointer Exception using getTilte(); Selenium with Java

Have two classes one Login and the other which is the TestNG class, I created variable to get the Title of the page but when trying to run the test it is displaying null pointer exception, if I remove the getTitle variable it runs.
package main;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Login {
WebDriver driver ;
By userNameTextBox = By.name("email");
By passwordTestBox = By.id("password");
By loginButton = By.id("signInButton");
String titleText = driver.getTitle();
public Login(WebDriver driver) {
this.driver=driver;
}
public void setUserName() {
driver.findElement(userNameTextBox).sendKeys("v-tobias.rivera#shutterfly.com");
}
public void setPassword() {
driver.findElement(passwordTestBox).sendKeys("Indecomm1");
}
public void clickLogin() {
driver.findElement(loginButton).click();;
}
}
package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
//import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
//import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import main.Login;
public class LoginTest {
WebDriver driver;
Login objLogin;
#BeforeMethod
public void beforeTest() {
System.setProperty("chromedriver", "/Users/tobiasriveramonge/eclipse-
workspaceAutomation/seleniumAutomation");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://accounts.shutterfly.com/?
redirectUri=https%3A%2F%2Fwww.shutterfly.com%2F&cid=&brand=SFLY&theme=SFLY");
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));
WebElement element =
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("email")));
element.isDisplayed();
}
#Test
public void Test() {
objLogin = new Login(driver);
//String title = objLogin.getTitle();
// System.out.println(title);
//Assert.assertTrue(loginPageTitle.toLowerCase().contains(" "));
objLogin.setUserName();
objLogin.setPassword();
objLogin.clickLogin();
}
#AfterTest
public void afterTest() {
driver.quit();
}
}
I would like to know why am I getting this exception.
Hi, Have two classes one Login and the other which is the TestNG class, I created variable to get the Title of the page but when trying to run the test it is displaying null pointer exception, if I remove the getTitle variable it runs.
You did not initialize the driver object.
That's why referencing to that not initialized object throws the null pointer exception.
You only declared the driver object type by
WebDriver driver;
but never initialized it.

POM not working on multiple test of TestNG

Below are my classes of POM:
Home
package com.sec.page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Home {
private WebDriver driver;
#FindBy(linkText = "Frequency Calculator")
WebElement frqcalc_page;
#FindBy(linkText = "Radial O-ring Selector")
WebElement radslct_page;
public Home(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public Freq_Calc clickFreqCalcPage() {
frqcalc_page.click();
return PageFactory.initElements(driver,Freq_Calc.class);
}
public Radial_Selector clickRadialSelectorPage() {
radslct_page.click();
return PageFactory.initElements(driver,Radial_Selector.class);
}
}
Freq_Calc
package com.sec.page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Freq_Calc {
private WebDriver driver;
#FindBy(linkText = "Bearing Frequencies Calculator")
WebElement BrgFreqCalc;
#FindBy(linkText = "Gearbox Calculator")
WebElement GearCalc;
#FindBy(linkText = "Overview")
WebElement overview_page;
public Freq_Calc(WebDriver driver){
this.driver=driver;
}
public Freq_Calc_BrgFreqCalc clickBrgFreqCalc(){
BrgFreqCalc.click();
return PageFactory.initElements(driver, Freq_Calc_BrgFreqCalc.class);
}
}
Radial_Selector
package com.sec.page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public class Radial_Selector {
private WebDriver driver;
#FindBy(name = "boreDiameter")
WebElement boreDiameter;
#FindBy(name = "boreTolerance")
WebElement boreTolerance;
#FindBy(css = "input[value='Calculate']")
WebElement calculate;
public Radial_Selector(WebDriver driver){
this.driver=driver;
}
public Radial_Selector enterboreDiameter(String value) {
boreDiameter.sendKeys(value);
return PageFactory.initElements(driver, Radial_Selector.class);
}
public Radial_Selector enterboreTolerance(String value) {
boreTolerance.sendKeys(value);
return PageFactory.initElements(driver, Radial_Selector.class);
}
public Radial_Selector clickcalculate() {
calculate.click();
return PageFactory.initElements(driver, Radial_Selector.class);
}
}
TestBase
package com.sec.util;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import com.sec.page.Freq_Calc;
import com.sec.page.Home;
import com.sec.page.Radial_Selector;
public class TestBaseSEC {
protected WebDriver driver=null;
protected String baseUrl;
protected Home homePage;
protected Radial_Selector radialselector;
protected Freq_Calc freqcalc;
#BeforeTest
public void setUp() {
baseUrl = "http://10.177.2.60:8080/engcalc/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#AfterTest
public void tearDown() throws Exception {
driver.quit();
}
}
Testcase:
package com.sec.scripts;
import org.openqa.selenium.By;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import com.sec.page.Home;
import com.sec.util.TestBaseSEC;
public class TestCaseSEC extends TestBaseSEC{
#Test
public void Test_RadialSelector_Page() throws Exception {
homePage = PageFactory.initElements(driver, Home.class);
driver.get(baseUrl);
radialselector = homePage.clickRadialSelectorPage();
radialselector.enterboreDiameter("10");
radialselector.enterboreTolerance("12");
radialselector.clickcalculate();
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span")).click();
}
#Test
public void Test_Freq_Calc_BrgFreqCalc_Page() throws Exception {
homePage = PageFactory.initElements(driver, Home.class);
freqcalc = homePage.clickFreqCalcPage();
}
}
My isssue is:
Whenn I run Testcase, The first #Test works fine. but when it goes to second #Test, where "freqcalc =homePage.clickFreqCalcPage()"is used, it tells there is no locator for Frequency Calculator, but that exist.
Also if I use "freqcalc =homePage.clickFreqCalcPage()" as last line in first #Test then it works.
So I want to understand why it does not work for second #Test.
You have to take care of a lot of things in your code as follows :
Loading the page elements even before accessing the url makes no sense. Hence first load the URL then initialize the WebElements on the Page Object.
When you initialize a Page Object get back the object in return.
driver.get(baseUrl);
Home homePage = PageFactory.initElements(driver, Home.class);
Use the returned Page Object to access it's methods.
homePage.clickRadialSelectorPage();
Avoid chaining of Page Objects i.e. initialization of another Page Object through return statement, rather initialize the required Page Object in your Test class.
//avoid
return PageFactory.initElements(driver,Radial_Selector.class);
//within Test Class
Radial_Selector radialselector = PageFactory.initElements(driver,Radial_Selector.class);
radialselector.enterboreDiameter("10");
As you are having seperate Page Objects for different pages try to define the locators e.g. xpath for the associated WebElement in the respective Page Objects only.
//avoid
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span"));
As you are having seperate Page Objects for different pages try to define the Page Object Methods e.g. click() for the WebElement's in the respective Page Factory only.
//avoid
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span")).click();
First #Test works fine because, though you try to initialize Home.class nothing really happens. When driver.get(baseUrl); gets executed the elements gets initialized and your #Test gets passed. But that's not the case with Second #Test. Hence Fails
The problem here is that, the URL is not launched in the second test when the page got initialized because it is missed in the second test.
Solution 1:
Please add the line driver.get(baseUrl) in your second test as given below.
#Test
public void Test_Freq_Calc_BrgFreqCalc_Page() throws Exception {
driver.get(baseUrl);
homePage = PageFactory.initElements(driver, Home.class);
freqcalc = homePage.clickFreqCalcPage();
}
Solution 2: Move the launch URL step to before Test method. Then remove it in first test as given below.
#BeforeTest
public void setUp() {
baseUrl = "http://10.177.2.60:8080/engcalc/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);
}
then remove it in the first test as given below.
#Test
public void Test_RadialSelector_Page() throws Exception {
homePage = PageFactory.initElements(driver, Home.class);
// driver.get(baseUrl);
radialselector = homePage.clickRadialSelectorPage();
radialselector.enterboreDiameter("10");
radialselector.enterboreTolerance("12");
radialselector.clickcalculate();
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span")).click();
}

isEnabled() failed to find element

I am new to selenium. I trying to check whether button is enable or not through isEnabled(). But when I am running this program it generating a error as "Unable to locate element" of button.
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class test
{
static WebDriver driver;
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "D:\\rakesh\\software\\selenium browser\\New folder\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://app.crossover.com/");
driver.manage().window().maximize();
JavascriptExecutor js= (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,5500)", "");
driver.findElement(By.linkText("Available Jobs")).click();
Boolean search_btn_ele = driver.findElement(By.xpath(".//*[#id='available-jobs']/div[2]/form/div/div[3]/button")).isEnabled();
if(search_btn_ele.FALSE)
{
System.out.println("Button is disable before giving search keys");
}
else
{
System.out.println("Button is enable before giving search keys");
}
WebElement search_txtfield_ele= driver.findElement(By.xpath(".//*[#id='available-jobs']/div[2]/form/div/div[1]/div/input"));
search_txtfield_ele.sendKeys("Chief");
}
}
Use WebDriverWait to wait for the element to be present:
new WebDriverWait(driver, TimeSpan.FromSeconds(45)).Until(ExpectedConditions.ElementIsVisible((By.Id("ctl00_ContentPlaceHolder1_drp85"))));

Can't able to call method from multiple classes in selenium webdriver

I am trying access method from two classes in another class but only one class method is called. during call of another class method it gives NullpointerException error. Please give me solution.
Code is here--->
Setup class-->
package BasePOI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Setup {
public WebDriver driver;
public void Websiteopen() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("url");
}
public Setup(WebDriver driver){
this.driver=driver;
}
}
Login page object class--->
package BasePOI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPOI {
public WebDriver driver;
//home
By home_login=By.linkText("Login");
By about_us=By.linkText("About Us");
//login
By counselor=By.id("counselor_login");
By user=By.id("user_login");
By username=By.id("username");
By password=By.id("password");
By Login=By.name("Login");
By create_account=By.name("Login");
By Logout=By.linkText("Logout");
public LoginPOI(WebDriver driver){
this.driver=driver;
}
public void click_Login_button(){
try {
driver.findElement(home_login).click();
}
catch (Exception e)
{
System.out.println(e);
}
}
public void click_Login_counselor(){
driver.findElement(counselor).click();
}
public void click_Login_user(){
driver.findElement(user).click();
}
public void Enter_login_data(String uname,String pwd){
driver.findElement(username).clear();
driver.findElement(username).sendKeys(uname);
driver.findElement(password).clear();
driver.findElement(password).sendKeys(pwd);
}
public void click_Login(){
driver.findElement(Login).click();
}
}
Now i am calling both classes method in another class
Login functionlity class--->
package Functionlity;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import BasePOI.LoginPOI;
import BasePOI.Setup;
public class Login {
public WebDriver driver;
#Test
public void openwebsite() throws InterruptedException{
Setup a= new Setup(driver);
a.Websiteopen();
Thread.sleep(10000);
LoginPOI b=new LoginPOI(driver);
b.click_Login_button();
}
}
Here website method is running but click_Login_button method gives me
errorerror--->
java.lang.NullPointerException
The Error is because the driver under LoginPOI class is not initialized. Change your code as per below and try -
Setup Class
package BasePOI;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Setup {
public static WebDriver driver;
public void Websiteopen()
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("url");
}
public Setup(WebDriver driver)
{
this.driver=driver;
}
public Setup()
{
}
public WebDriver getDriver()
{
return this.driver;
}
}
Login POI
package BasePOI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPOI
{
public WebDriver driver;
//home
By home_login=By.linkText("Login");
By about_us=By.linkText("About Us");
//login
By counselor=By.id("counselor_login");
By user=By.id("user_login");
By username=By.id("username");
By password=By.id("password");
By Login=By.name("Login");
By create_account=By.name("Login");
By Logout=By.linkText("Logout");
public void click_Login_button(){
try {
this.driver=new Setup().getDriver();
driver.findElement(home_login).click();
}
catch (Exception e)
{
System.out.println(e);
}
}
public void click_Login_counselor()
{
driver.findElement(counselor).click();
}
public void click_Login_user()
{
driver.findElement(user).click();
}
public void Enter_login_data(String uname,String pwd)
{
driver.findElement(username).clear();
driver.findElement(username).sendKeys(uname);
driver.findElement(password).clear();
driver.findElement(password).sendKeys(pwd);
}
public void click_Login()
{
driver.findElement(Login).click();
}
}
Login Class
package Functionlity;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Login
{
public WebDriver driver;
#Test
public void openwebsite() throws InterruptedException
{
Setup a= new Setup(driver);
a.Websiteopen();
LoginPOI b=new LoginPOI();
b.click_Login_button();
}
}
Explanation :
First need to make webderiver static under Setup class to make same driver accessible to different instances
create one default constructor in setup class and one method which return driver to access in another classes
this.driver=new Setup().getDriver(); will get the (initialized driver instances in setup class) driver in LoginPOI class
You are not initializing the driver object in your test class and that's why it throws null pointer exception when calling any webdriver method inside Page class.
The simple solution would be to modify your setup class and initialize the webdriver in setup method
Setup class
public class Setup {
public Webdriver getDriver() {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("url");
}
public Setup(WebDriver driver){
this.driver=driver;
}}
Test Class
public class Login {
public WebDriver driver;
#BeforeMethod
public void setup() {
driver = new FirefoxDriver();
}
#Test
public void openwebsite() throws InterruptedException{
Setup a = new Setup(driver);
a.Websiteopen();
LoginPOI b=new LoginPOI(driver);
b.click_Login_button();
}}

Can any one help me , my Test Ng annotations are not running .In the Below code my #before class only running but not other

In the below code i am trying to automate gmail by data driven frame work using TestNg , but my code #Before annotation only executing not other two .Please healp me.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class LoginData {
WebDriver driver;
#Test
public void login() {
driver.findElement(By.linkText("Sign in")).click();
System.out.println("hello");
}
#BeforeTest
public void beforeTest() throws Exception {
WebDriver driver=new FirefoxDriver();
driver.get("https://www.gmail.com/intl/en/mail/help/about.html");
Thread.sleep(2000);
}
#AfterTest
public void fterTest() {
driver.close();
}
}
Since you have declared WebDriver driver already;
remove Webdriver from WebDriver driver==new FirefoxDriver();
I tried below and worked for me.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class LoginData1 {
WebDriver driver;
#Test
public void login() {
driver.findElement(By.linkText("Sign in")).click();
System.out.println("hello");
}
#BeforeTest
public void beforeTest() throws Exception {
driver=new FirefoxDriver();
driver.get("https://www.gmail.com/intl/en/mail/help/about.html");
Thread.sleep(2000);
}
#AfterTest
public void fterTest() {
driver.close();
}
}
Accept if it works for you or let me know if this does not work...
Thanks