I have created 3 different classes like SelectBrowserTest, GmailLoginPOTest and SampleTest (this is my test case). i tried to call the methods from SelectBrowserTest and GmailLoginPOTest to SampleTest. But, Am continuously getting Null pointer exception. Can any one help to solve this?
Code
SampleTest:
package TestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.*;
import TCPSampleProject.SelectBrowserTest;
import pageObjects.GmailLoginPOTest;
public class SampleTest{
static WebDriver driver;
private static GmailLoginPOTest g1;
#BeforeMethod
public void OpenBrowser() {
SelectBrowserTest open = new SelectBrowserTest();
open.ChromeBrowser();
}
#AfterMethod
public void CloseBrowser() {
SelectBrowserTest close = new SelectBrowserTest();
close.Close();
}
#Test(priority = 0)
public static void GmailLogin() {
g1 = PageFactory.initElements(driver, GmailLoginPOTest.class);
g1.GmailLink.click();
System.out.println("Gmail Link clicked");
g1.SignInLink.click();
g1.EmailIDTextBox.sendKeys("rvigneshprabu");
g1.EmailNextButton.click();
g1.PasswordTextBox.sendKeys("Password");
g1.PswdNextButton.getText();
System.out.println("Gmail Login Completed");
}
}
GmailLoginPOTest:
package pageObjects;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class GmailLoginPOTest{
#FindBy(linkText = "Gmail")
public WebElement GmailLink;
#FindBy(xpath = ".//a[contains(text(),'Sign In')]")
public WebElement SignInLink;
#FindBy(id = "identifierId")
public WebElement EmailIDTextBox;
#FindBy(id = "identifierNext")
public WebElement EmailNextButton;
#FindBy(name = "password")
public WebElement PasswordTextBox;
#FindBy(id = "passwordNext")
public WebElement PswdNextButton;
}
SelectBrowserTest:
package TCPSampleProject;
import java.io.File;
import java.io.IOException;
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;
public class SelectBrowserTest {
WebDriver driver;
public void ChromeBrowser() {
System.setProperty("webdriver.chrome.driver",
"//Users//vigneshprabur//Documents//Automation//Drivers//chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
public void Close() {
driver.quit();
System.out.println("Browser Closed");
}
public void ScreenShot() {
try {
File ScrShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(ScrShot, new File("/Users/vigneshprabur/Documents/Automation/Screenshots/image_"+System.currentTimeMillis()+".png"));
System.out.println("Screenshot Taken");
}
catch (IOException e) {
System.out.println("Exception While Taking Screenshot" + e.getMessage());
}
}
}
These 3 are my class files. While running the script am getting the following error message.
Output:
FAILED CONFIGURATION: #AfterMethod CloseBrowser
java.lang.NullPointerException
at TCPSampleProject.SelectBrowserTest.Close(SelectBrowserTest.java:29)
at TestCases.SampleTest.CloseBrowser(SampleTest.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:455)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:643)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:716)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:988)
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)
FAILED: GmailLogin
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy9.click(Unknown Source)
at TestCases.SampleTest.GmailLogin(SampleTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:580)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:716)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:988)
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)
Please try the below code.In your SampleTest class the driver is null.Thats why you got null pointer exception.
SampleTest.java
package TestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.*;
import TCPSampleProject.SelectBrowserTest;
import pageObjects.GmailLoginPOTest;
public class SampleTest{
static WebDriver driver;
private static GmailLoginPOTest g1;
SelectBrowserTest open;
#BeforeMethod
public void OpenBrowser() {
open = new SelectBrowserTest();
open.ChromeBrowser();
driver = open.getDriver();
}
#AfterMethod
public void CloseBrowser() {
open.Close();
}
#Test(priority = 0)
public static void GmailLogin() {
g1 = PageFactory.initElements(driver, GmailLoginPOTest.class);
g1.GmailLink.click();
System.out.println("Gmail Link clicked");
g1.SignInLink.click();
g1.EmailIDTextBox.sendKeys("rvigneshprabu");
g1.EmailNextButton.click();
g1.PasswordTextBox.sendKeys("Password");
g1.PswdNextButton.getText();
System.out.println("Gmail Login Completed");
}
}
SelectBrowserTest .java
package TCPSampleProject;
import java.io.File;
import java.io.IOException;
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;
public class SelectBrowserTest {
WebDriver driver;
public WebDriver getDriver() {
return driver;
}
public void ChromeBrowser() {
System.setProperty("webdriver.chrome.driver",
"//Users//vigneshprabur//Documents//Automation//Drivers//chromedriver");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
public void Close() {
driver.quit();
System.out.println("Browser Closed");
}
public void ScreenShot() {
try {
File ScrShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(ScrShot, new File("/Users/vigneshprabur/Documents/Automation/Screenshots/image_"+System.currentTimeMillis()+".png"));
System.out.println("Screenshot Taken");
}
catch (IOException e) {
System.out.println("Exception While Taking Screenshot" + e.getMessage());
}
}
}
Related
I am using TestNG and Page Object Model.
I have created some test cases. I see that the first two test cases are working. But, the third test case starts on a new page which is opened by the second test case. I am unable to interact with the new page, and getting a Null Pointer Exception error. Not sure what went wrong.
I have three Java classes Here.
This is my base class:
package MYQC_Reusable_Classes;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
public class MYQC_Base_Class {
public static WebDriver driver = null;
// public static ExtentTest Logger = null;
// public static ExtentReports report = null;
#BeforeSuite
public void initialize() throws IOException {
// report = new ExtentReports("C:\\Users\\fhasan\\Desktop\\ExtentReport"+".html");
System.setProperty("webdriver.chrome.driver", "C:\\Users\\fhasan\\Desktop\\driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();`enter code here`
// add the precondition arguments
options.addArguments("start-maximized", "incognito");
driver = new ChromeDriver(options);
// To maximize browser
driver.manage().window().maximize();
// Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#BeforeMethod
public void timer(){
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#AfterSuite
// Test cleanup
public void TeardownTest() throws InterruptedException {
Thread.sleep(4000);
MYQC_Base_Class.driver.quit();
}
}
This is my page class:
package MYQC_Browser_Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class MYQC_Login_Page {
WebDriver driver;
// constructor that will be automatically called as soon as the object of the
// class is created
public MYQC_Login_Page(WebDriver driver) {
this.driver = driver;
}
#FindBy(how = How.ID, using = "loginName")
public static WebElement userNameField;
#FindBy(how = How.ID, using = "loginPassword")
public static WebElement passwordField;
#FindBy(how = How.ID, using = "loginButton")
public static WebElement clickLogin;
//Method to enter username
public void clickUserName() {
userNameField.click();
}
public void enterUserName(String user) {
userNameField.sendKeys(user);
}
public void clickPass() {
passwordField.click();
}
public void enterPassword(String pass) {
passwordField.sendKeys(pass);
}
//Method to click on Login button
public void clickLoginButton() {
clickLogin.click();
}
}
This is my first test case which works fine:
package MYQC_TestCase_Classes;
import MYQC_Browser_Pages.CUST4_MYQC_Login_Selection_Page;
import MYQC_Reusable_Classes.MYQC_Base_Class;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.util.PriorityQueue;
public class TC001_MYQC_Login_Selection_Button_Text extends MYQC_Base_Class {
#Test()
public void MYQC_Login_Button_Text() throws InterruptedException, IOException {
//creating anb object of the CUST4_MYQC_Login_Selection_Page
CUST4_MYQC_Login_Selection_Page go_To_MYQC_Page = PageFactory.initElements(driver, CUST4_MYQC_Login_Selection_Page.class);
// going to the cust4 myqc link
driver.get("https://mmhcustfour.com");
Thread.sleep(3000);
Assert.assertEquals(go_To_MYQC_Page.buttonText(), "Login with Quickcharge Authentication");
//System.out.print( go_To_MYQC_Page.buttonText());
}
}
This is my second test case (on the same page) which also works fine:
package MYQC_TestCase_Classes;
import MYQC_Browser_Pages.CUST4_MYQC_Login_Selection_Page;
import MYQC_Browser_Pages.MYQC_Login_Page;
import MYQC_Reusable_Classes.MYQC_Base_Class;
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.support.PageFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
public class TC002_MYQC_Login_Selection_Test extends MYQC_Base_Class {
#Test
public void Go_To_MYQC_Login_Page_Test() throws InterruptedException, IOException {
//creating anb object of the CUST4_MYQC_Login_Selection_Page
CUST4_MYQC_Login_Selection_Page go_To_MYQC_Page = PageFactory.initElements(driver, CUST4_MYQC_Login_Selection_Page.class);
//Clicking on the button to go to the MYQC login page
go_To_MYQC_Page.preClickLogin();
// waiting few seconds to get a screenshot of the page
Thread.sleep(2000);
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("C:\\Users\\fhasan\\Desktop\\Selenium Screenshots\\MYQCLogin_Page.png"));
Thread.sleep(2000);
}
}
This is my third test case class: (which creates the error)
package MYQC_TestCase_Classes;
import MYQC_Browser_Pages.MYQC_Login_Page;
import MYQC_Reusable_Classes.MYQC_Base_Class;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TC003_MYQC_Prepaid_Login_Test extends MYQC_Base_Class {
//creating an object of the page
MYQC_Login_Page login_page = PageFactory.initElements(driver,MYQC_Login_Page.class);
#Test
public void MYQC_Login() throws InterruptedException {
Thread.sleep(2000);
login_page.clickUserName();
login_page.enterUserName("***");
Thread.sleep(2000);
login_page.clickPass();
login_page.enterPassword("***");
login_page.clickLoginButton();
}
}
After running the code, I am getting the following error:
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy9.click(Unknown Source)
at MYQC_Browser_Pages.MYQC_Login_Page.clickUserName(MYQC_Login_Page.java:30)
at MYQC_TestCase_Classes.TC003_MYQC_Prepaid_Login_Test.MYQC_Login(TC003_MYQC_Prepaid_Login_Test.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1198)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1123)
at org.testng.TestNG.run(TestNG.java:1031)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:109)
your username element is not found on your 3rd test, please do following actions
at MYQC_Browser_Pages.MYQC_Login_Page.clickUserName(MYQC_Login_Page.java:30)
Please add screenshot just before entering username,
Add wait time to load website completely.
still not helpful,
better you should isolate all your test methods.
no static properties
login and logout should be in before method and after method - test method should be independent
use common method for assertions so whenever get failed, automatically add screenshot
Am Facing Issues While Runnig Cross Browser,
The issue is it is opening the browser but not navigating to the URL i Provided and Start the Test.
i Have Created Totally 3 Packages ,
1. Browser Configuration (package) - BrowserSetup.java (File)
2.TestCase (Package) - FinalTest.java(file)
3 Test Methods(Package) - List of All Methods for each Single Page(Files)
My Issue, if i don't import the Browsersetup.java inside the finaltest.java for Calling The Browser, it is Sucessfully running and test get passed. but When i Import the BrowserSetup.java inside the finalTest.java, it is Not Working Properly Down i have attached Both File of Code
BrowserSetup.java
package Browserconfiguration;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class Browsersetup
{
WebDriver driver;
public WebDriver setup(String browser) throws Exception
{
//Check if parameter passed from TestNG is 'firefox'
if(browser.equalsIgnoreCase("firefox"))
{
//create firefox instance
System.setProperty("webdriver.gecko.driver", "F:\\New folder\\geckodriver.exe");
driver = new FirefoxDriver();
}
//Check if parameter passed as 'chrome'
else if(browser.equalsIgnoreCase("chrome"))
{
//set path to chromedriver.exe
ChromeOptions options = new ChromeOptions();
options.setAcceptInsecureCerts(true);
options.setBinary(new File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"));
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");
//create chrome instance
driver = new ChromeDriver(options);
}
//Check if parameter passed as 'Edge'
else if(browser.equalsIgnoreCase("Edge"))
{
//set path to IE.exe
System.setProperty("webdriver.edge.driver","F:\\New folder (2)\\MicrosoftWebDriver (1).exe");
//create Edge instance
driver = new EdgeDriver();
}
else
{
//If no browser passed throw exception
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
FinalTest.java
public class FinalTest {
WebDriver driver;
#BeforeTest
public void beforeTest() throws Exception
{
Browsersetup obj = new Browsersetup();
obj.setup("chrome");
driver.get("http://xxx.xxxxxxxxxxxx.xxx/");
List<WebElement> links=driver.findElements(By.tagName("a"));
System.out.println("Total links are "+links.size());
for(int i=0;i<links.size();i++)
{
WebElement ele= links.get(i);
String url=ele.getAttribute("href");
verifyLinkActive(url);
}
}
//Finding the broken Links in the website.
private void verifyLinkActive(String linkUrl) {
try
{
URL url = new URL(linkUrl);
HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
httpURLConnect.setConnectTimeout(3000);
httpURLConnect.connect();
if(httpURLConnect.getResponseCode()==200)
{
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
}
if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)
{
System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
}
} catch (Exception e) {
}
}
}
Please, Clarify Me Where My Issue i can't find it
Error:
java.lang.NullPointerException
at TestCase.FinalTest.beforeTest(FinalTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:59)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:455)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:222)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:142)
at org.testng.TestRunner.beforeRun(TestRunner.java:529)
at org.testng.TestRunner.run(TestRunner.java:497)
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)
Actually in FinalTestClass you're using another Webdriver, Try to do the following:
Use the driver which is returning from obj.setup("chrome");
public class FinalTest {
WebDriver driver;
#BeforeTest
public void beforeTest() throws Exception
{
Browsersetup obj = new Browsersetup();
driver = obj.setup("chrome");
driver.get("http://xxx.xxxxxxxxxxxx.xxx/");
//...........
}
Just try it and let me know if it didn't work.
My files and error which iI am getting are as follows:
url_title.properties
username=rakeshm#techved.com
password=123456
chrome_driver_path=D://rakesh//software//selenium browser//chrome 2.28//chromedriver.exe
BrowserFactory class file
package utilities;
import java.io.File;
import java.io.FileInputStream;
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.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class BrowserFactory
{
static Properties browserfactory_properties_obj;
static WebDriver driver;
public static WebDriver browser_factory_getter(String browser, String url) throws IOException
{
File browserfactory_file_obj = new File(".\\src\\property_folder\\url_title.properties");
FileInputStream browserfactory_fileinput_obj = new FileInputStream(browserfactory_file_obj);
browserfactory_properties_obj = new Properties();
browserfactory_properties_obj.load(browserfactory_fileinput_obj);
if(browser.equalsIgnoreCase("firefox"))
{
ProfilesIni profile = new ProfilesIni();
FirefoxProfile fire_profile = profile.getProfile("selenium_browser");
driver = new FirefoxDriver(fire_profile);
}
else if(browser.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver",browserfactory_properties_obj.getProperty("chrome_driver_path"));
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
home_login_elements class file
package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class home_login_elements
{
WebDriver driver;
#FindBy(how=How.CLASS_NAME, using="login")
WebElement login_link_ele;
#FindBy(how=How.ID, using="email")
WebElement username_ele;
#FindBy(how=How.ID, using="passwd")
WebElement password_ele;
#FindBy(how=How.ID, using="SubmitLogin")
WebElement login_submint_ele;
public WebElement login_link()
{
login_link_ele.click();
return login_link_ele;
}
public void login_fun(String username, String password)
{
username_ele.sendKeys(username);
password_ele.sendKeys(password);
login_link_ele.submit();
}
}
login_class class file
package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class login_class
{
WebDriver driver;
Properties login_class_url_title;
public login_class() throws Exception
{
File login_class_url_title_file = new File(".\\src\\property_folder\\url_title.properties");
FileInputStream login_class_url_title_fis = new FileInputStream(login_class_url_title_file);
login_class_url_title = new Properties();
login_class_url_title.load(login_class_url_title_fis);
home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
}
}
Add_to_wishlist testng file(executable file)
package wishlist;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import utilities.BrowserFactory;
import utilities.home_login_elements;
import utilities.login_class;
public class Add_to_wishlist extends home_login_elements
{
WebDriver driver;
#Test
public void first_testcase() throws Exception
{
driver = BrowserFactory.browser_factory_getter("chrome", "http://automationpractice.com/index.php");
login_class obj =new login_class();
driver.findElement(By.xpath("//ul[#class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']/li[3]")).click();
}
}
After executing Add_to_wishlist testng file i am getting following error
Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 6905
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: first_testcase
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.sendKeys(Unknown Source)
at utilities.home_login_elements.login_fun(home_login_elements.java:36)
at utilities.login_class.<init>(login_class.java:20)
at wishlist.Add_to_wishlist.first_testcase(Add_to_wishlist.java:17)
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:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
The problem is, you are not in login/sign in page. you have missed to click on sign in link in home page. please call the method login_link before calling the login_fun in the class login_class as given below.
driver=BrowserFactory.driver;
home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
home_login_elements_login_class_obj.login_link();//This is missing in your code
home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
Your login_class doesn't seem to know about your initialized driver, hence it is NULL.
In your case, make these changes:
In login_class change your constructor to take a driver:
public login_class(WebDriver webDriver) throws Exception
{
driver = webDriver;
...
}
In first_testcase():
{
...
login_class obj =new login_class(driver);
...
}
That being said... this is a weird implementation, and I would suggest looking at a few more examples of how others get this set up initially. But if it works for you then that's great :)
For what it's worth, I think the answer provided by #murthi would be sufficient to set the driver properly, and should probably be the accepted answer because it's the simplest way to do what you're asking.
I don't see the in the class you have initialize your element.
public class home_login_elements {
public home_login_elements(WebDriver driver) {
PageFactory.initElements(driver, this);
}
}
I am a new automation tester, Working on sample test scripts, Need some help from you guys, I have tried to use POM and basic TestNG.
I have created 2 packages - pages and testcases.
I am getting some error when I am trying to access the "ClickJoin, Enterusername" methods from my pages packages. I had tried figuring out the issue, but was unable to get to why this error is occurring.
Below is the Error:
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull
My Code from the "pages" package:
package com.gptoday.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Login {
public WebDriver driver;
public WebDriverWait wait;
By join = By.xpath("//*[#id='members']/a[1]");
By username = By.id("username");
By password = By.id("password");
By loginButton = By.xpath("//*[#id='normallogin']/div[4]/p/input[2]");
public Login (WebDriver driver){
this.driver=driver;
}
public void ClickJoin(){
wait = new WebDriverWait(driver,10);
//driver.findElement(join).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(join)).click();
}
public void EnterUsername(){
wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(username)).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(username)).sendKeys("Test username");
System.out.println("Username Entered");
}
public void EnterPassword(){
driver.findElement(password).clear();
driver.findElement(password).click();
System.out.println("Password Entered");
}
public void ClickButton(){
wait = new WebDriverWait(driver, 10);
//driver.findElement(loginButton).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(loginButton)).click();
System.out.println("Login Button Clicked");
}
}
My Code from the "TestCases" package:
This code is of my base class.
package com.gptoday.com.gptoday.testcases;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.testng.annotations.AfterMethod;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Base {
public WebDriver driver;
#BeforeMethod
public void BaseSetup(){
ProfilesIni prof = new ProfilesIni();
FirefoxProfile ffProfile= prof.getProfile ("vishvesh");
ffProfile.setAcceptUntrustedCertificates(true);
ffProfile.setAssumeUntrustedCertificateIssuer(false);
String BaseUrl = "https://www.gptoday.com";
System.setProperty("webdriver.gecko.driver", "G:/Workplace/AutomationSetupFiles/Geckdriver/geckodriver.exe");
driver = new FirefoxDriver (ffProfile);
driver.get(BaseUrl);
driver.manage().window().maximize();
}
#AfterMethod
public void afterTest() {
System.out.println("Success");
}
}
**Below the the code for the test case.**
package com.gptoday.com.gptoday.testcases;
import org.testng.annotations.Test;
import com.gptoday.pages.Login;
import org.openqa.selenium.WebDriver;
public class LoginVerification extends Base {
public WebDriver driver;
public Login obj = new Login(driver);
#Test
public void Verify()
{
obj.ClickJoin();
obj.EnterUsername();
}
}
**Error:**
Success
FAILED: Verify
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:770)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:96)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:71)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:45)
at com.gptoday.pages.Login.ClickJoin(Login.java:22)
at com.gptoday.com.gptoday.testcases.LoginVerification.Verify(LoginVerification.java:16)
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:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
Here's the reason behind the error you are getting:
In both Login & EnterUsername methods while you defined the wait you have passed the instance of Webdriver & interval. Now whenever Selenium detects this particular type of argument Selenium treats this as FluentWait. Now when you actually implement a FluentWait you have to import those two libraries "com.google.common.base.Function" which will address the error you are facing. Of course you have to import "FluentWait" as well.
Let me know if this helps you.
By modifying the code in the "Login.Java" class.. The issue was related to driver being null as I did not extend "Base" in the "Login" class.
I am quite new to Selenium WebDriver. A java.lang.NullPointerException has been troubling me for sometime now, and I cannot understand why. Following are my classes which are quite simple actually:
suiteBase.java
package utilities.suiteBase;
import org.openqa.selenium.WebDriver;
import actions.testPage1.testPage1Actions;
import ui_map.testPage1.TestPage1UI;
public class suiteBase {
public WebDriver driver;
protected static TestPage1UI tpui = new TestPage1UI();
protected static testPage1Actions tpa = new testPage1Actions();
}
testPage1Actions.java
package actions.testPage1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.WebElement;
import utilities.suiteBase.suiteBase;
public class testPage1Actions extends suiteBase {
public WebDriver driver;
public void test(WebDriver driver){
WebElement loc1 = driver.findElement(By.xpath("id('email')"));
loc1.sendKeys("testing");
System.out.println("done...");
}
}
TestPage1.java
package testPage1;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utilities.suiteBase.BrowserOpen;
import utilities.suiteBase.suiteBase;
public class TestPage1 extends suiteBase{
public WebDriver driver;
BrowserOpen browse = new BrowserOpen();
#Parameters({ "browserType", "appURL" })
#Test(priority = 1)
public void openBrowser(String browserType, String appURL){
browse.setUp(browserType, appURL);
System.out.println("Done....");
}
#Test(priority = 2)
public void testCase1() throws InterruptedException{
driver.wait(1000);
tpa.test(driver);
}
}
I run the TestPage1.java file using XML, where I encounter following error:
java.lang.NullPointerException at
testPage1.TestPage1.testCase1(TestPage1.java:28) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) at
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767) at
org.testng.TestRunner.run(TestRunner.java:617) at
org.testng.SuiteRunner.runTest(SuiteRunner.java:334) at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) at
org.testng.SuiteRunner.run(SuiteRunner.java:240) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1198) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1123) at
org.testng.TestNG.run(TestNG.java:1031) at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:137)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:58)
Also I have browserOpen class which I run before TestPage1, in which I declare the WebDriver
package utilities.suiteBase;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import utilities.suiteBase.BrowserOpen;
public class BrowserOpen {
public WebDriver driver;
static String driverPath = "E:\\Selenium\\";
public void setUp(String browserType, String appURL) {
try {
setDriver(browserType, appURL);
} catch (Exception e) {
System.out.println("Error....." + e.getStackTrace());
}
}
#AfterClass
public void tearDown() {
driver.quit();
}
private void setDriver(String browserType, String appURL) {
switch (browserType) {
case "chrome":
driver = initChromeDriver(appURL);
break;
case "firefox":
driver = initFirefoxDriver(appURL);
break;
default:
System.out.println("browser : " + browserType
+ " is invalid, Launching Firefox as browser of choice..");
driver = initFirefoxDriver(appURL);
}
}
private static WebDriver initChromeDriver(String appURL) {
System.out.println("Launching google chrome with new profile..");
System.setProperty("webdriver.chrome.driver", driverPath + "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(appURL);
System.out.println("URL inserted");
// driver.get(appURL);
return driver;
}
private static WebDriver initFirefoxDriver(String appURL) {
System.out.println("Launching Firefox browser..");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to(appURL);
return driver;
}
}
I never used this technology before, but I see not inited elements.
public WebDriver driver;
WebDriver was not initialized.
You need to initialize them before using.
Like:
WebDriver driver = new FirefoxDriver();
Or something else. Check this out: http://www.seleniumhq.org/docs/03_webdriver.jsp
-- UPD: Exception is probably throwing at testCase1() tpa.test(WebDriver). tpa is probably null.
you are using #Parameters({ "browserType", "appURL" }) in your TestPage1 class that will come from testng.xml file . Hope your using this xml file to run your test.
When I declared - public static WebDriver driver; before #BeforeSuite
and then inside the method if we again declared as
WebDriver driver = new FirefoxDriver();
and run the script then it shows me java.lang.NullPointerException error.
Please try below code to resolve :-
driver = new Firefoxdriver();
Example -
public class LearnCheckBox {
public static WebDriver driver;
#BeforeSuite
public static void verify_SetupBrowser() throws InterruptedException
{
driver = new FirefoxDriver(); //
driver.get("https://learn.letskodeit.com/p/practice");
driver.manage().window().maximize();
Thread.sleep(2000);
}
Ashish Bind