Two firefox browser windows open in my selenium - java

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")));
// ...
}
}

Related

Not able to execute two #Test in pageFactory

<-Here is the base BaseClass which is extends by VerifyLoginTest & this will open driver->
public class BaseClass {
private static Properties prop;
protected static WebDriver driver;
protected static WebDriverWait wait;
#BeforeSuite
public void propReading() {
try {
File file = new File(ConstantPaths.PROP_PATH);
FileInputStream fileInputStream = new FileInputStream(file);
prop = new Properties();
prop.load(fileInputStream);
} catch (
IOException e) {
System.out.println("Properties file not found");
}
}
public static void initializeBrowser() //Selenium 4.6.0 after that
{
switch (prop.getProperty("browserName").toUpperCase()) {
case "CHROME":
driver = new ChromeDriver();
ChromeOptions options = new ChromeOptions();
//options.addArguments("kiosk-printing");
break;
case "FIREFOX":
driver = new FirefoxDriver();
break;
case "EDGE":
driver = new EdgeDriver();
default:
System.out.println("Illegal Browser Name");
break;
}
driver.manage().window().maximize();
driver.get(prop.getProperty("urlName"));
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
public static void closeBrowser() {
driver.close();
}
}
While running same #test in pageFactory model it is giving invalidSessionId exception
package testscripts;//import java.util.*;
import actions.Actions;
import base.BaseClass;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pagesobjects.HomePage;
public class VerifyLoginTest extends BaseClass{
#BeforeMethod
public void startBrowser()
{
BaseClass.initializeBrowser();
}
#Test
public void verifyNoValue(){
HomePage homePage = HomePage.getHomePageObj();
homePage.enterInvestmentAmount(" ");
homePage.clickOnCalculate();
Assert.assertEquals(homePage.getErrorMsg(),"This field is required");
Actions.takeScreenshot("verifyNoValue");
}
#Test
public void verifyMinValue(){
HomePage homePage = HomePage.getHomePageObj();
homePage.enterInvestmentAmount("499");
homePage.clickOnCalculate();
Assert.assertEquals(homePage.getErrorMsg(),"Min Amount is 500");
Actions.takeScreenshot("verifyMinValue");
}
#Test
public void verifyMaxValue(){
HomePage homePage = HomePage.getHomePageObj();
homePage.enterInvestmentAmount("50000001");
homePage.clickOnCalculate();
Assert.assertEquals(homePage.getErrorMsg(),"Min Amount is 500");
Actions.takeScreenshot("verifyMinValue");
}
#AfterMethod
public void tearDown(){
BaseClass.closeBrowser();
}
}
This #Test are running in one browser instance only, I am expecting it to run on different browser as I have added 3 test annotation with before method

java.lang.NullPointerException for TestNG classes

Hello guys I am getting error while running below TestNG test.
public class BaseTest {
WebDriver driver;
#BeforeClass
public void LaunchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "c://chromedriver.exe");
WebDriver driver = new ChromeDriver();
Thread.sleep(5000);
driver.get("https://stackoverflow.com/questions/26032149/selenium-testng-java-lang-nullpointerexception");
System.out.println("1");
driver.manage().window().maximize();
Thread.sleep(10000);
}
}
public class Homepage extends BaseTest
{
WebDriver driver;
#Test
public void Discover() {
driver.findElement(By.xpath("/html/body/header/div/ol[1]/li/a")).click();
}
}
Error:
1
FAILED: Discover
java.lang.NullPointerException
at pages.Homepage.Discover(Homepage.java:16)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
Null point exception occurring because of driver instance you are initiating begin differently than later.
Please create and use driver instance as a global variable
static WebDriver driver;
-------------------------------------------------------------------------------------------
OR
Singleton is solution for null point exception in your test automation
Create class and by using method you can use driver instance any where without any issue like null point
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.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class TestApp {
private WebDriver driver;
private static TestApp myObj;
// public static WebDriver driver;
utils.PropertyFileReader property = new PropertyFileReader();
public static TestApp getInstance() {
if (myObj == null) {
myObj = new TestApp();
return myObj;
} else {
return myObj;
}
}
//get the selenium driver
public WebDriver getDriver()
{
return driver;
}
//when selenium opens the browsers it will automatically set the web driver
private void setDriver(WebDriver driver) {
this.driver = driver;
}
public static void setMyObj(TestApp myObj) {
TestApp.myObj = myObj;
}
public void openBrowser() {
//String chromeDriverPath = property.getProperty("config", "chrome.driver.path");
//String chromeDriverPath = property.getProperty("config", getChromeDriverFilePath());
System.setProperty("webdriver.chrome.driver", getChromeDriverFilePath());
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void navigateToURL() {
String url =property.getProperty("config","url");
;
driver.get(url);
}
public void closeBrowser()
{
driver.quit();
}
public WebElement waitForElement(By locator, int timeout)
{
WebElement element = new WebDriverWait(TestApp.getInstance().getDriver(), timeout).until
(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private String getChromeDriverFilePath()
{
// checking resources file for chrome driver in side main resources
URL res = getClass().getClassLoader().getResource("chromedriver.exe");
File file = null;
try {
file = Paths.get(res.toURI()).toFile();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
}
//If you want call driver instance you can use following line
**TestApp.getInstance().getDriver();**

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

Getting selenium support pagefactory DefaultElementLocator findElement nullpointerexception for driver

I am creating page object model plus data driver framework.
I am writing Testcase for logIn but getting pagefactory nullpointerexception.
1. How I can initialise my driver in order to avoid this error?
2. Again How I can Sccreenshot page class in my test script i have given code below.
FAILED: Log("s#gmail.com", "sw45")
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
TestBase class
public class TestBase {
public WebDriver driver;
public void initialize() throws InterruptedException, IOException {
System.out.println("Launching browser");
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\admin\\eclipse-workspace\\SampleProject\\src\\main\\java\\selenium\\org\\sample\\SampleProject\\data\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.navigate().to("http://automationpractice.com/index.php?controller=authentication&back=my-account");
Thread.sleep(6000);
}
}
AppTest java
public class AppTest extends ExcelReader {
TestBase TB = new TestBase();
#BeforeTest
void browserlaunch() throws InterruptedException, IOException
{
TB.initialize();
}
#Test(dataProvider = "testdata")
public void LogIn(String email, String pwd) throws IOException, InterruptedException {
System.out.println("Sign in page1");
SignIn loginpage = PageFactory.initElements(driver, SignIn.class);
loginpage.setUserName(email);// email entered
loginpage.setPwd(pwd);// password entered
loginpage.Sign_In_btn();
driver.manage().window().maximize();
try {
Assert.assertEquals(driver.getTitle(), "My account - My Store");
System.out.println("Log IN successfull1");
} catch (AssertionError E) {
System.out.println("Log IN un-successfull" + E);
}
Thread.sleep(8000);
System.out.println("after click");
}
}
Screenshotpage java
public class ScreenshotPage extends TestBase {
private WebDriver driver = new ChromeDriver();
public void ScreenshotPage1() throws InterruptedException, IOException {
Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
.takeScreenshot(driver);
ImageIO.write(fpScreenshot.getImage(), "PNG", new File("D:/selenium/" + System.currentTimeMillis() + ".png"));
}
}
Make this method to return WebDriver :
public WebDriver initialize() throws InterruptedException, IOException {
System.out.println("Launching browser");
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\admin\\eclipse-workspace\\SampleProject\\src\\main\\java\\selenium\\org\\sample\\SampleProject\\data\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.navigate().to("http://automationpractice.com/index.php?controller=authentication&back=my-account");
Thread.sleep(6000);
return driver;
}
and in AppTest class use it as :
public class AppTest extends ExcelReader {
public WebDriver driver;
TestBase TB = new TestBase();
#BeforeTest
void browserlaunch() throws InterruptedException, IOException
{
driver = TB.initialize();
}
For screenshot make your method as :
public static void ScreenshotPage1(WebDriver driver) throws InterruptedException, IOException {
Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
.takeScreenshot(driver);
ImageIO.write(fpScreenshot.getImage(), "PNG", new File("D:/selenium/" + System.currentTimeMillis() + ".png"));
}
and after #Test use in AppTest class :
#AfterMethod
public void takeScreenShot() throws InterruptedException, IOException {
ScreenshotPage.ScreenshotPage1(driver);
}
package com.xyz33;
import java.util.concurrent.TimeUnit;
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 DemoPOMclass {
//static WebDriver driver;
static String url1="https://www.facebook.com/";
static WebDriver driver;
public DemoPOMclass(WebDriver driver) {
this.driver=driver; PageFactory.initElements(driver, this);// initElements() method will create all WebElements
}
#FindBy(name="email")
WebElement userID;
#FindBy(id="pass")
WebElement passwrd;
#FindBy(id="u_0_d_Ek")
WebElement btn_login;
public WebDriver launchBrowser() {//just open chrome browser using automation
System.setProperty("webdriver.chrome.driver" ,"C:/Users/tgt193/Desktop/traningAll/AllDrivers/chromedriver.exe" );
System.out.println("browser is launch successfully");
driver=new ChromeDriver();//type casting
driver.manage().window().maximize(); //maximizes the open browser
System.out.println("browser maximize sussfully");
return driver;
}
public WebDriver openUrl(String url1) {//open URL using automation
driver.get(url1);
System.out.println("URL is launch successfully");
return driver;
}
public void enterUserName(String uName){
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
System.out.println("wait 3 sec ");
System.out.println("enter username at FB page");
userID.sendKeys(uName);
System.out.println("username enter successfully at FB page");
}
public void enterPassword(String uPasswd){
passwrd.sendKeys(uPasswd);
System.out.println("enter password at FB page");
}
public void click_onLogInButton(){
btn_login.click();
}
public void login_ToFB() {
this.launchBrowser();
this.openUrl("https://www.facebook.com/");
this.enterUserName("sunit");
this.enterPassword("sunit123#");
this.click_onLogInButton();
}
public static void main(String[] args) {
DemoPOMclass objPOM =new DemoPOMclass(driver);
objPOM.launchBrowser();
objPOM.openUrl(url1);
objPOM.enterUserName("sunit");
objPOM.enterPassword("sunit123");
//objPOM.login_ToFB();
//objPOM.login_ToFB();
}
}

Page Object Factory - NullPointerException

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.

Categories

Resources