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

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

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.

How Can I implement Hooks In Cucumber as a separate Class file?

This is the baseclass.
package utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import io.github.bonigarcia.wdm.WebDriverManager;
public class BaseClass {
public static WebDriver driver;
public WebDriverWait wait;
public static Properties prop;
FileInputStream fis;
static String browserName;
String currentDir = System.getProperty("user.dir");
public BaseClass()
{
prop=new Properties();
try {
fis = new FileInputStream(currentDir + "/src/test/java/config/data.properties");
} catch (FileNotFoundException e1) {
}
try {
prop.load(fis);
} catch (IOException e) {
}
}
public static void initialization()
{
browserName = prop.getProperty("browser");
if (browserName.equalsIgnoreCase("Chrome"))
{
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
else if(browserName.contains("Firefox"))
{
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
else
{
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(prop.getProperty("url"));
}
}
This is login page
package Pages;
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;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import utils.BaseClass;
public class LoginPage extends BaseClass {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver= ldriver;
wait = new WebDriverWait(driver, 90);
PageFactory.initElements(driver, this);
}
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[1]//parent::div")
WebElement radioAccount;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[2]//parent::div")
WebElement radioVcNumber;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[3]//parent::div")
WebElement macId;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[4]//parent::div")
WebElement vSc;
#FindBy(how=How.XPATH, using="(//*[#type='radio'])[5]//parent::div")
WebElement rMn;
#FindBy(how=How.XPATH,using="//*[#id='txt_InputVal']")
WebElement enterRmn;
#FindBy(how=How.XPATH, using="//*[#id='btnsubmit']")
WebElement buttonSubmit;
public void clickRadioButtons()
{
wait.until(ExpectedConditions.visibilityOf(radioAccount));
radioAccount.click();
radioVcNumber.click();
macId.click();
vSc.click();
rMn.click();
}
public void loginWithRmn(String num)
{
rMn.click();
wait.until(ExpectedConditions.visibilityOf(enterRmn));
enterRmn.sendKeys(num);
}
public void clickOnLoginButton()
{
buttonSubmit.click();
}
}
This is step definition of login page.
package stepDefs;
import Pages.LoginPage;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import utils.BaseClass;
public class LoginStepDef extends BaseClass{
LoginPage login;
String title;
#Given("^User has launched URL on browser$")
public void user_has_launched_URL_on_browser()
{
BaseClass.initialization();
System.out.println("Browser Launched");
login = new LoginPage(driver);
}
#Given("^User is able to select different account types$")
public void user_is_able_to_select_different_account_types()
{
login = new LoginPage(driver);
login.clickRadioButtons();
}
#When("^User enters tries to login with Mobile Number \"([^\"]*)\"$")
public void user_enters_tries_to_login_with_Mobile_Number(String arg1)
{
login.loginWithRmn(arg1);
}
#Then("^User is logged in$")
public void user_is_logged_in()
{
login.clickOnLoginButton();
}
#After()
public void tearDown()
{
System.out.println("Browser Closed");
driver.quit();
}
}
This is test runner.
package runners;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features= {"src/test/java/featureFiles"},
glue= {"stepDefs"},
monochrome=true,
dryRun=false,
plugin= {"pretty"}
)
public class TestRunnerLogin {
}
How can I implement Hooks ?
Hooks as a different class file(Hooks.java) so that I don't have to write invoke browser again and again for further pages.
I want Hooks.java as a separate class and not implemented in some step definition.
this is my HOOKS file. maybe this can help you:
public class Hooks {
public static WebDriver driver;
#Before
public void startTest(Scenario scenario) {
System.setProperty("webdriver.chrome.driver", "src/test/resources/mac/chromedriver");
driver = new ChromeDriver();
driver.get("http://google.com");
}
#After
public void tearDown(Scenario scenario) {
Helper.screenshot(scenario);
driver.close();
}
public static WebDriver getDriver() { 
return driver;
}
}
and follow how to use:
public class LoginSteps {
private LoginPage loginPage = new LoginPage(Hooks.getDriver());
#When("something")
public void signCheck()  {
Assert.assertTrue("Login", homePage.checkPage());
}
}

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

Getting NullPointerException when trying to access Selenium Webdriver instance in below scenario.

I am trying to create a framework where I can run my test cases(test tags in xml file) in parallel in different browsers. I have tried using all combinations of testNG annotations but after reading a blog came to know that this can only be achieved by using testNg listners. I am using ThreadLocal to keep my driver thread-safe. I am getting null pointer exception when trying to access Webdriver in my test cases class in line LocalDriverManager.getDriver().get(url);
This is LocalBrowserFactory.Class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import DataProvider.ConfigDataProvider;
public class LocalDriverFactory {
public static WebDriver createInstance(String browserName) {
WebDriver driver = null;
ConfigDataProvider config=new ConfigDataProvider();
if (browserName.toLowerCase().contains("firefox")) {
System.setProperty("webdriver.gecko.driver", config.getgeckoPath());
driver = new FirefoxDriver();
}
if (browserName.toLowerCase().contains("internet")) {
driver = new InternetExplorerDriver();
}
if (browserName.toLowerCase().contains("chrome")) {
System.setProperty("webdriver.chrome.driver", config.getchromePath());
driver = new ChromeDriver();
}
driver.manage().window().maximize();
return driver;
}
}
This is my LocalDriverManager.class
package BrowserFactory;
import org.openqa.selenium.WebDriver;
public class LocalDriverManager {
private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return webDriver.get();
}
public static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
}
This is my ConfigPropertyReader.class
package DataProvider;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class ConfigDataProvider {
static Properties p;
public ConfigDataProvider()
{
File f =new File("C:/Eclipse/parallelframework/configuration/config.properties");
try {
FileInputStream fis = new FileInputStream(f);
p=new Properties();
p.load(fis);
}
catch (Exception e)
{
System.out.println("Custom Exception- cannot load properties file"+e.getMessage());
}
}
public String getvalue(String key)
{
return p.getProperty(key);
}
public String getUrl()
{
return p.getProperty("url");
}
public String getchromePath()
{
return p.getProperty("chromepath");
}
public String getgeckoPath()
{
return p.getProperty("firefoxpath");
}
public String getIEPath()
{
return System.getProperty("User.dir")+p.getProperty("IEPath");
}
}
This is WebDriverListner.class
package Listners;
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import BrowserFactory.LocalDriverFactory;
import BrowserFactory.LocalDriverManager;
public class WebDriverListner implements IInvokedMethodListener {
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
System.out.println(browserName);
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
System.out.println("Driver Set");
}
}
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
This is my sample testcase.class
package tests;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import BrowserFactory.LocalDriverManager;
public class sampleTest {
#Test
public void testMethod1() {
invokeBrowser("http://www.ndtv.com");
}
#Test
public void testMethod2() {
invokeBrowser("http://www.facebook.com");
}
private void invokeBrowser(String url) {
LocalDriverManager.getDriver().get(url);
}
}
Your Listener code is messed up. You basically have the beforeInvocation and afterInvocation in the wrong order.
Here's how it should have looked like
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class WebDriverListener implements IInvokedMethodListener {
#Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
}
}
#Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
You basically would setup the webdriver into the thread local variable (push the webdriver instance into the thread local variable's context) from within the beforeInvocation and then within your afterInvocation method, you would pop it out and clean up the webdriver instance (by calling quit() ). In your case, your code is doing the opposite.
For more details you can refer to my blog post here.

Selenium Pagefactory-I get Null pointer. WebElement is initialized. Implemented page object pattern

I'm very new to OOP and Java. I came across this excellent video of page object factory on page object pattern:https://www.youtube.com/watch?v=u8XH46u1QAw. I tried to implement a similar code for a basic yahoo site and I get a Null pointer error. Can you please help me in troubleshooting this? I appreciate your time. My code is using testNG
Error from console:
FAILED: execute
java.lang.NullPointerException
at PageObject.SearchPage.updateSearch(SearchPage.java:16)
Code:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import PageObject.SearchPage;
public class PgMain {
WebDriver Browser;
#BeforeTest
public void start(){
Browser=new InternetExplorerDriver ();
}
#Test
public void execute(){
SearchPage s=new SearchPage(Browser);
s.navigateTo();
s.updateSearch();//This is when I get the NPE
}
#AfterTest
public void stop(){
}
}
package PageObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public abstract class Abs {
WebDriver Browser;
public Abs(WebDriver Browser){
this.Browser=Browser;
}
public SearchPage navigateTo(){
Browser.get("http://finance.yahoo.com/");
return PageFactory.initElements(Browser, SearchPage.class);
}
}
package PageObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class SearchPage extends Abs {
#FindBy (id="UHSearchProperty")
private WebElement searchFinancebtn;
#FindBy (id="UHSearchBox")
private WebElement usersearchBox;
public SearchPage(WebDriver Browser){
super(Browser);
}
public SearchPage updateSearch(){
usersearchBox.sendKeys("GOOG");//NPE
searchFinancebtn.click();
return PageFactory.initElements(Browser, SearchPage.class);
}
}
you initElements only on the returned instance of SearchPage during navigateTo() call.
so for your code to work you'd have to do the following:
SearchPage s = new SearchPage(Browser);
s.navigateTo().updateSearch();
but to be honest this looks very ugly. Why not just to do the following:
WebDriver driver;
SearchPage searchPage;
#Before
public void start() {
driver = new InternetExplorerDriver();
searchPage = PageFactory.initElements(driver, SearchPage.class);
}
#Test
public void execute() {
s.navigateTo();
s.updateSearch();
}
Also I'd question the excellence of that video.