Null pointer Exception with Page Factory - selenium-webdriver

I was doing some coding to learn PageFactory, but I am getting this error when trying to call a method in another class using page factory
Below is my Elements class:
package pulse.pom.tpr;
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.interactions.Actions;
import org.testng.annotations.Test;
public class PulseElements {
WebDriver driver;
public Actions actions;
// Login Page Elements
#FindBy(how = How.NAME, using = "userId")
WebElement userid;
#FindBy(name = "password")
WebElement password;
#FindBy(name = "dcNumber")
WebElement dcnbr;
#FindBy(css = "body > ion-app > ng-component > ion-nav > page-login > ion-content > div.scroll-content > ion-card > ion-grid > form > ion-list > div.login-button > button > span")
WebElement login;
// TPR button Element
#FindBy(id = "tab-t0-2")
WebElement tpr;
// Send Associate button
#FindBy(xpath = "//*[#id='tabpanel-t0-2']/tpr-summary-page/ion-header[2]/ion-grid/ion-row/ion-col[3]/ion-row/button[1]")
WebElement sendasc;
// Next Button after selecting associate
#FindBy(xpath = "//*[#id='footers']/ion-toolbar/div[2]/ion-row/ion-col[2]/button")
WebElement next1;
// Next Button after selecting Area
#FindBy(xpath = "//*[#id='tabpanel-t0-2']/tpr-send-associates-page/div/ion-footer/button")
WebElement next2;
// Clockin Button
#FindBy(xpath = "//*[#id='tabpanel-t0-2']/tpr-send-associates-page/ion-content/div[2]/div/div/ion-row[2]/ion-col/div[1]")
WebElement clockin;
public PulseElements(WebDriver driver) {
this.driver = driver;
actions = new Actions(driver);
}
#Test(priority = 1)
public void pulseLogin(String uid, String pwd, String dc) {
actions.moveToElement(userid).click().sendKeys(uid);
actions.build().perform();
actions.pause(java.time.Duration.ofSeconds(1));
actions.moveToElement(password).click().sendKeys(pwd);
actions.build().perform();
actions.pause(java.time.Duration.ofSeconds(1));
actions.moveToElement(dcnbr).click().sendKeys(dc);
actions.build().perform();
actions.pause(java.time.Duration.ofSeconds(1));
actions.moveToElement(login).click();
actions.build().perform();
}
#Test(priority = 2)
public void tprClick() {
actions.moveToElement(tpr).click();
actions.build().perform();
}
#Test(priority = 3)
public void sendAssociateButton() {
actions.moveToElement(sendasc).click();
actions.build().perform();
}
public void selectNext1() {
actions.moveToElement(next1).click();
actions.build().perform();
}
public void selectNext2() {
actions.moveToElement(next2).click();
actions.build().perform();
}
public void selectClockin() {
actions.moveToElement(clockin).click();
actions.build().perform();
}
}
And below is my 1st test class for my login page:
package pulse.pom.tpr;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
public class PulseLogin {
public WebDriver driver;
//public PulseElements locateElements=PageFactory.initElements(driver, PulseElements.class);
#Test(priority=1)
public void pulseLoginPage() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver",
"C:\\MyChromeDriver\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://mysite/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
PulseElements locateElements=PageFactory.initElements(driver, PulseElements.class);
locateElements.pulseLogin("sysadmin", "1234#", "7036");
locateElements.tprClick();
locateElements.sendAssociateButton();
}
#Test(priority=2)
public void selectAssociate() {
System.out.println("Please select any associate");
Scanner asc = new Scanner(System.in);
asc.close();
}
#Test(priority=3)
public void selectNextButton1(){
PulseElements locateElements=PageFactory.initElements(driver, PulseElements.class);
locateElements.selectNext1();
}
#Test(priority = 4)
public void selectArea() {
System.out.println("Please select area");
Scanner area = new Scanner(System.in);
area.close();
}
#Test(priority=5)
public void selectNextButton2()
{
PulseElements locateElements=PageFactory.initElements(driver, PulseElements.class);
locateElements.selectNext2();
}
}
And my 2nd test class:
package pulse.pom.tpr;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
public class ClockinToClockout {
public WebDriver driver;
public PulseLogin login=PageFactory.initElements(driver,PulseLogin.class);
#Test(priority=1)
public void launchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\MyChromeDriver\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
login.pulseLoginPage();
login.selectAssociate();
login.selectNextButton1();
login.selectArea();
login.selectNextButton2();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test(priority=2)
public void makeMove() {
PulseElements ele=PageFactory.initElements(driver, PulseElements.class);
ele.selectClockin();
}
}
Everything else is working fine, but the makeMove() function in my 2nd test class is giving a null pointer exception:
PASSED: launchBrowser
FAILED: makeMove
java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:51)
at com.sun.proxy.$Proxy7.getCoordinates(Unknown Source)
at org.openqa.selenium.interactions.internal.MouseAction.getActionLocation(MouseAction.java:65)
at org.openqa.selenium.interactions.MoveMouseAction.perform(MoveMouseAction.java:43)
at org.openqa.selenium.interactions.CompositeAction.perform(CompositeAction.java:36)
at org.openqa.selenium.interactions.Actions$BuiltAction.perform(Actions.java:641)
at pulse.pom.tpr.PulseElements.selectClockin(PulseElements.java:100)
at pulse.pom.tpr.ClockinToClockout.makeMove(ClockinToClockout.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

That's because you need to initialise the PulseElements at the class level and not at the #Test level like you have done it for PulseLogin class.
So, initialise the PulseElements at the class level like:
public class ClockinToClockout {
public WebDriver driver;
public PulseLogin login=PageFactory.initElements(driver,PulseLogin.class);
public PulseElements ele=PageFactory.initElements(driver, PulseElements.class);
#Test(priority=1)
public void launchBrowser() throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\MyChromeDriver\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
login.pulseLoginPage();
login.selectAssociate();
login.selectNextButton1();
login.selectArea();
login.selectNextButton2();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test(priority=2)
public void makeMove() {
ele.selectClockin();
}
}

Related

Selenium-webdriver is giving me blank screen of google chrome and a Java null pointer exception. Can anyone suggest?

TestBase which contains the intialization method which is creating problem :
package TestBase;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
public class testBasesetup {
public static Properties prop;
public static WebDriver driver;
public static testBasesetup testBaseObj;
public static EventFiringWebDriver e_driver;
public testBasesetup() throws Exception
{
try {
prop = new Properties();
File src = new File("C:\\Users\\LENOVO\\eclipse-workspace\\Demon\\src\\main\\java\\Config\\config.properties");
FileInputStream ip = new FileInputStream(src) ;
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization() throws Exception
{
String browsername = prop.getProperty("browser");
if(browsername.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", "F:\\Eclipse\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
}
else if(browsername.equals("firefox"))
{
System.setProperty("webdriver.gecko.driver", "F:\\Eclipse\\browser\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
String URLtoTest = prop.getProperty("URL");
Thread.sleep(1000);
}
}
Test Class which I am running and this is creating issue. I guess there is some issue with driver variable but don't know the error:
package PageTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
import TestBase.testBasesetup;
public class LoginPageTest extends testBasesetup{
LoginPage LoginPageObj;
testBasesetup testBaseObj;
public LoginPageTest() throws Exception
{
super();
}
#BeforeMethod
public void setup() throws Exception
{
initialization();
LoginPageObj = new LoginPage();
Thread.sleep(2000);
}
#Test()
public void LoginCheck() throws Exception
{
LoginPageObj.login("first.customer#kkr.com","Potatok");
}
#AfterMethod
public void tearDown()
{
driver.quit();
}
}
Image of error:
Code
Your static instance of WebDriver remain uninitialized. You need to initialize static instance instead of local driver instance in initialization() method. Like Below:
public class testBasesetup {
public static Properties prop;
public static WebDriver driver;
public static testBasesetup testBaseObj;
public static EventFiringWebDriver e_driver;
public testBasesetup() throws Exception
{
try {
prop = new Properties();
File src = new File("C:\\Users\\LENOVO\\eclipse-workspace\\Demon\\src\\main\\java\\Config\\config.properties");
FileInputStream ip = new FileInputStream(src) ;
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization() throws Exception
{
String browsername = prop.getProperty("browser");
if(browsername.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", "F:\\Eclipse\\chromedriver.exe");
**driver = new ChromeDriver();**
}
else if(browsername.equals("firefox"))
{
System.setProperty("webdriver.gecko.driver", "F:\\Eclipse\\browser\\geckodriver.exe");
**driver = new FirefoxDriver();**
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
String URLtoTest = prop.getProperty("URL");
Thread.sleep(1000);
}
}

unable to locate the password field in gmail .getting the error "webdriver exception"

import java.util.concurrent.TimeUnit;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Withtestng {
private WebDriver driver;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
System.setProperty("webdriver.gecko.driver", "/usr/bin/geckodriver");
System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testGmailLogInHtml() throws Exception {
driver.get("https://www.google.com/");
driver.findElement(By.linkText("Gmail")).click();
driver.findElement(By.xpath("/html/body/nav/div/a[2]")).click();
driver.findElement(By.id("identifierId")).click();
driver.findElement(By.id("identifierId")).clear();
driver.findElement(By.id("identifierId")).sendKeys("xyz#gmail.com");
driver.findElement(By.xpath("//div[#id='identifierNext']/content")).click();
driver.findElement(By.xpath("//input[#class='whsOnd zHQkBf']")).click();
driver.findElement(By.xpath("//input[#class='whsOnd zHQkBf']")).clear();
driver.findElement(By.xpath("//input[#class='whsOndzHQkBf']")).sendKeys("xyz");***
driver.findElement(By.xpath("//div[#id='passwordNext']/content/span"))click();
driver.findElement(By.xpath("//div[#id='gb']/div/div/div[2]/div[5]/div/a/span")).click();
driver.findElement(By.id("gb_71")).click();
}
Your script execution speed and page load time is not in sync, try to use
pageLoadTimeout.
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);//
Or
You can wait for particular condition becomes true(ie. wait until element present using wait.until) and then perform operation on it.

how to call function/method form one class to another class in selenium webdriver using java

I want to call login and search method from two different class into the main class. I have written the two diff classes for login and search but when I am calling both method in class containg main method .it gives me an error as below>>
Exception in thread "main" java.lang.NullPointerException
at Test_package_Ted_baker.search.search_1(search.java:14)
at Test_package_Ted_baker.SHopping.main(SHopping.java:16)
Can someone please help me to find out solution about how to call methods from one class to another class. My code is as below>>
Main class
package Test_package_Ted_baker;
import org.openqa.selenium.WebDriver;
public class SHopping {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
login_Ted_Baker obj=new login_Ted_Baker();
obj.login_to_Ted_Baker("ss3777010#gmail.com", "google#123");
System.out.println("Login sucessfully");
search obj1=new search();
obj1.search_1();
obj.user_logout();
System.out.println("User log out sucessfully");
}
}
Login class
package Test_package_Ted_baker;
import java.util.HashMap;
import java.util.Map;
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.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class login_Ted_Baker {
WebDriver driver;
public static void main (String [] args) throws InterruptedException
{
login_Ted_Baker obj=new login_Ted_Baker();
obj.login_to_Ted_Baker("ss3777010#gmail.com", "google#123");
System.out.println("Login Sucessfully");
obj.user_logout();
}
public void usename( String Username)
{
WebElement Username_TB=driver.findElement(By.name("j_username"));
Username_TB.sendKeys(Username);
}
public void password(String Password)
{
WebElement Password_TB=driver.findElement(By.name("j_password"));
Password_TB.sendKeys(Password);
}
public void submit()
{
driver.findElement(By.xpath(".//*[#id='command']/div/input ")).click();
}
public void login_Ted_Baker(WebDriver driver){
this.driver = driver;
}
public void user_logout() throws InterruptedException
{
Thread.sleep(1000);
WebElement Sign_in_link=driver.findElement(By.xpath(".//*[#id='page']/header/div/nav[1]/ul/li[3]/div/a"));
WebElement Sign_out_button=driver.findElement(By.xpath(".//*[#id='account']/ul/li[2]/a"));
Thread.sleep(1000);
Actions Act1=new Actions(driver);
Act1.moveToElement(Sign_in_link).click();
Act1.moveToElement(Sign_out_button).click().build().perform();
System.out.println("Logout sucessfully");
}
public void login_to_Ted_Baker(String Username,String Password) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver_win32\\chromedriver.exe");
//System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
Thread.sleep(2000);
ChromeOptions options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
try{
driver.get("http://www.tedbaker.com/");
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")));
if(driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).isDisplayed())
{
driver.findElement(By.xpath("html/body/div[3]/div[2]/div/div/ul/li[1]/a")).click();
}
driver.findElement(By.xpath(".//*[#id='page']/header/div/nav[1]/ul/li[3]/div/a")).click();
Thread.sleep(2000);
this.usename(Username);
this.password(Password);
this.submit();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
searching class
package Test_package_Ted_baker;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
public class search {
WebDriver driver;
public void search_1() throws InterruptedException
{
WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
Search_Item.click();
WebElement Seacrh_item_message=driver.findElement(By.id("search"));
WebElement Search_textbox=driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[1]/input"));
Search_textbox.sendKeys("Watches");
driver.findElement(By.xpath("html/body/div[2]/header/div/form/div[1]/ol/li[2]/input")).click();
WebElement SearchResult_pagemessage=driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/h1"));
driver.findElement(By.xpath("html/body/div[2]/div/div/div[1]/div/div/div/span[1]")).click();
WebElement Item_Tobuy = driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[2]/div[1]/article/div[2]/header/div/h4/a"));
JavascriptExecutor jse1= (JavascriptExecutor)driver;
jse1.executeScript("window.scrollBy(0,400)", "");
Item_Tobuy.click();
driver.findElement(By.xpath("html/body/div[2]/div/div/div[2]/div[1]/section[2]/form/ol/li[2]/span/span/select")).click();
Select dropdown1=new Select(driver.findElement(By.id("qty")));
dropdown1.selectByVisibleText("1");
driver.findElement(By.id("qty")).click();
// driver.findElement(By.xpath("*[#classname='button add_to_cart major full_mobile colour_dark']/div[2]/div[1]/div/input[1]")).click();
// driver.findElement(By.xpath("//*[#id='add_to_cart_form']/div[2]/div[2]/a/span[1]/span[1]")).click();
driver.findElement(By.xpath("//input[contains(#class,'add_to_cart')]")).click();
Thread.sleep(1000);
Actions act=new Actions(driver);
WebElement My_cart_button=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[3]/a/span[2]"));
//WebElement My_cart_button=driver.findElement(By.xpath("//input[contains(#class,'My bag')]"));
WebElement View_bag_checkout_button=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[3]/div/ul/li/a"));
act.moveToElement(My_cart_button).moveToElement(View_bag_checkout_button).click().build().perform();
driver.findElement(By.xpath("html/body/div[2]/div/div/div/section/table/tbody/tr/td[2]/form/ul/li[2]/a")).click();
String Cart_empty_mesg=driver.findElement(By.xpath("html/body/div[1]/div/div/div/header/h1")).getText();
System.out.println(Cart_empty_mesg);
String Actual_cart_empty_msg="Your shopping bag is empty";
if(Cart_empty_mesg==Actual_cart_empty_msg)
{
System.out.println("Cart is empty, you can add product cart");
}
}
}
This might sound harsh, but first of all you should read about
Null Pointer Exception from this link.
How to debug from a StackTrace from this link.
Why using absolute xpath, or xpaths locators in general is a bad strategy from here.
From your stack trace,
Exception in thread "main" java.lang.NullPointerException at
Test_package_Ted_baker.search.search_1(search.java:14) at
Test_package_Ted_baker.SHopping.main(SHopping.java:16)
I see that your code in Search class
WebElement Search_Item=driver.findElement(By.xpath("html/body/div[2]/header/div/nav[2]/section/ul[2]/li[1]/a/span[1]"));
is not correct. I suspect your locator is not correct for this one. The element can easily be identified using an id attribute, as
driver.findElement(By.id("search"));
or , if you're using xpaths, then
driver.findElement(By.xpath("//*[#id="search"]"));
should do away the NPE - but not sure since you've used a lot of absolute xpaths - which is a horrible practise.

Error when executing testng.xml using pagefactory

I am running 2 classes using testNG.First class is running successfully but second class is failing with error:
"org.testng.TestNGException:Can't invoke public void TestScripts.NewAccountCreation.AccountCreation1(): either make it static or add a no-args constructor to your class"
If I add non argument constructor I am getting null pointer exception.
I am using Pagefactory to design my test cases.
Eclipse version:kepler
TestnG:6.9.9
Chrome version: 57.0.2987.133
Chrome driver: 2.27
Any suggestions would be greatly appreciated.
Please find the below code:
Page factory Code for Login Page:
/**
*
*/
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import Pages.LoginPage;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver = ldriver;
}
#FindBy(xpath = "//input[contains(#id,'username-inputEl')]")
public WebElement username;
#FindBy(xpath = "//input[contains(#id,'password-inputEl')]")
public WebElement password;
#FindBy(xpath = "//span[contains(#id,'submit-btnInnerEl')]")
public WebElement LoginButton;
// Methods to perform actions
public void pCLogin(String Username, String Password, WebDriver driver)
{
username.sendKeys(Username);
password.sendKeys(Password);
LoginButton.click();
}
}
Page Factory code for Account creation page:
package Pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
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.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Accounttab {
WebDriver driver;
public Accounttab(WebDriver ldriver)
{
this.driver = ldriver;
}
#FindBy(xpath = "//span[#id='TabBar:AccountTab-btnWrap']")
public WebElement accountDropDown;
#FindBy(xpath = "//span[contains(#id,'AccountTab_NewAccount-textEl')]")
public WebElement NewAccount_Button;
#FindBy(xpath = "//textarea[contains(#id,'GlobalContactNameInputSet:Name-inputEl')]")
public WebElement Companyname;
#FindBy(xpath = "//input[contains(#id,'OfficialIDDV_Input-inputEl')]")
public WebElement FEINNumber;
#FindBy(xpath = "//input[contains(#id,'GlobalAddressInputSet:City-inputEl')]")
public WebElement City;
#FindBy(xpath = "//input[contains(#id,'GlobalAddressInputSet:PostalCode-inputEl')]")
public WebElement Zipcode;
#FindBy(xpath = "//a[contains(#id,'SearchLinksInputSet:Search')]")
public WebElement AccountsearchButton;
#FindBy(xpath = "//span[#class='x-btn-inner x-btn-inner-center'][contains(#id,'NewAccountButton-btnInnerEl')]")
public WebElement CreateNewButton;
#FindBy(css = "input[id='TabBar:AccountTab:AccountTab_AccountNumberSearchItem-inputEl']")
public WebElement AccountSearch;
#FindBy(xpath = "//tbody[contains(#id,'gridview')]//tr[1]//td[2]")
public WebElement SelectAccountNumber;
public void accountMouseHover(WebDriver driver) {
WebDriverWait wait1 = new WebDriverWait(driver, 10);
wait1.until(ExpectedConditions.visibilityOf(accountDropDown));
Actions builder2 = new Actions(driver);
builder2.moveToElement(accountDropDown).moveByOffset(50, 0).click()
.build().perform();
System.out.println("Dropdown is opened");
}
public void accountSearch(String AccountName, WebDriver driver)
{
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions .visibilityOf(NewAccount_Button));
driver.manage().window().maximize();
Actions builder1 = new Actions(driver);
builder1.moveToElement(NewAccount_Button).click().build().perform();
System.out.println("Clicked on New Accounr Button");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Companyname.sendKeys(AccountName);
try {
AccountsearchButton.click();
} catch (Exception e) {
System.out
.println("Please enter one of the minimum required fields: Company Name, FEIN"
+ e);
throw (e);
}
wait.until(ExpectedConditions .visibilityOf(CreateNewButton));
CreateNewButton.click();
}
}
Test Scripts1:
LoginClass:
**
package TestScripts;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import Pages.LoginPage;
import Utility.Configreader;
import Utility.GenericMethods;
public class Login {
WebDriver driver;
LoginPage Login_page;
#BeforeSuite
public void setUp() {
Configreader cr = new Configreader(
"H://Selenium//Selenium_ODSRegression//TestData//config.properties");
driver = GenericMethods.startBrowser("Chrome", cr.getURL());
Login_page = PageFactory.initElements(driver, LoginPage.class);
}
#Test
public void PClogin() {
Login_page.pCLogin("su", "gw", driver);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
**
Test Script2:
AccountCreation class:
package TestScripts;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import Pages.AccountFileSummary;
import Pages.Accounttab;
import Pages.CreateNewAccount;
public class NewAccountCreation {
WebDriver driver;
Accounttab Account_tab1;
CreateNewAccount NewAccount1;
AccountFileSummary AFS1;
public NewAccountCreation(WebDriver ldriver)
{
this.driver = ldriver;
Account_tab1 = PageFactory.initElements(driver, Accounttab.class);
}
#Test
public void AccountCreation1() {
Account_tab1.accountMouseHover(driver);
Account_tab1.accountSearch("WebDriver_Test1", driver);
}
}
driver class:
package Utility;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import Utility.Configreader;
public class GenericMethods {
public static WebDriver driver = null;
static Configreader cr = new Configreader(
"H://Selenium//Selenium_ODSRegression//TestData//config.properties");
public static WebDriver startBrowser(String browsername, String URL)
{
if (browsername.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver",
cr.getChromeDriverPath());
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
else if (browsername.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", cr.getIEDriverPath());
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
}
driver.get(URL);
return driver;
}
}
Property file:
PCURL = http://biltipolicycenter.thehartford.com/pc/PolicyCenter.do
ChromeBrowserPath = C://Selenium//ChromeDriver 2.27//chromedriver.exe
IEBrowserPath = C://Selenium//IEDriverServer x86 2.53//IEDriverServer.exe
TestNG.XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="TestScripts.Login"/>
<class name="TestScripts.NewAccountCreation"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
NewAccountCreation is a test class because it contains test method(s) and because you declare it as a class test in the testng.xml.
So, it means TestNG must be able to create an instance of the class and that's why TestNG is complaining.
You have 2 options:
Using a factory to explain to TestNG how to create test classes
(best option IMO)
Using a static shared driver instance (Login#driver is not
yet static)
BTW, your organization of classes looks a bit dirty and you should rework them a bit.

Display Oracle Database content in JavaFX TableView

I want to display content of an Oracle Database in my TableView "FilmTable".
The structure of the Oracle Databade is: a table column named "FILMTITEL" in the table "LUKA1". The are 4 Film names like Fast and Furious, ...
Hope you can help me and i hope i understand your Solutions to solve my Problem.
I made this code and i got this Errors:
javafx.fxml.LoadException:
/D:/Users/muellerl/workspace/Table_DB/bin/application/gui.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at application.Main.start(Main.java:15)
at com.sun.javafx.application.LauncherImpl$8.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$7.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$6$1.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$6$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$4$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at controller.table_controller.initialize(table_controller.java:39)
... 20 more
If I remove all Table-Code-Contents the error isn't there.
Here is my code i hope you can help me to Display this things.
Main.java
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource(
"/application/gui.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
table_controller.java:
package controller;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import oracle.jdbc.*;
import model.filmtable_data;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class table_controller implements Initializable {
Connection conn;
String output;
int zaehler = 0;
#FXML
private TableView<filmtable_data> FilmTable;
#FXML
private TableColumn<filmtable_data, String> Filmtitel_col;
#FXML
private TableColumn<filmtable_data, Integer> ID_col;
#Override
public void initialize(URL location, ResourceBundle resources) {
// Observable List
final ObservableList<filmtable_data> data = FXCollections.observableArrayList();
ID_col.setCellValueFactory(new PropertyValueFactory<filmtable_data, Integer>("rID"));
Filmtitel_col.setCellValueFactory(new PropertyValueFactory<filmtable_data, String>("rFilmtitel"));
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:lukas/1234#10.140.79.39:1521:OTTO");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("SELECT FILMTITEL FROM LUKA1");
while (resultset.next()) {
output = resultset.getString(1);
zaehler++;
filmtable_data entry = new filmtable_data(zaehler, output);
data.add(entry);
System.out.println (resultset.getString(1));
System.out.println(output);
}
FilmTable.setItems(data);
statement.close();
} catch (SQLException e) {
System.out.println("Login fehlgeschlagen.");
e.printStackTrace();
}
}
}
filmtable_data.java:
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class filmtable_data {
private final SimpleIntegerProperty rID;
private final SimpleStringProperty rFilmtitel;
public filmtable_data (Integer sID, String sFilmtitel) {
this.rID = new SimpleIntegerProperty(sID);
this.rFilmtitel = new SimpleStringProperty(sFilmtitel);
}
public Integer getRID() {
return rID.get();
}
public void setRID(int set) {
rID.set(set);
}
public String getRFilmtitel() {
return rFilmtitel.get();
}
public void setRFilmtitel(String set) {
rFilmtitel.set(set);
}
}

Resources