I have implemented simple Login selenium framework using DataProvider.
I created a simple login page which contains username and password. I have also created excel file with login data and excel reader class as well. Seems that DataProvider within my test class fault.
I get the the information "java.lang.NullPointerException".I know that is something wrong with String in DataProvider, but if I changed to Object the issue is still as above.
Here is my code for testng:
package com.insurance.testCases;
import com.insurance.pageObjects.loginPage;
import com.insurance.utilities.excelReader;
import org.openqa.selenium.NoAlertPresentException;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
public class TC_LoginDdt_002 extends baseClass{
#Test(dataProvider = "loginData")
public void loginDDT(String user,String pwd){
driver.get(baseUrl);
loginPage lp=new loginPage(driver);
lp.setUserName(user);
lp.setPassword(pwd);
lp.clickSubmit();
if (isAlertPresent()==true){
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
Assert.assertTrue(false);
}
else {
Assert.assertTrue(true);
lp.clickLogout();
driver.switchTo().alert().accept();
driver.switchTo().defaultContent();
}
}
public boolean isAlertPresent(){
try {
driver.switchTo().alert();
return true;
}
catch (NoAlertPresentException e){
return false;
}
}
#DataProvider(name="loginData")
String [][] getData() throws IOException {
String path="C:/Users/lachi/IdeaProjects/InetBanking_v1/target/DataSet.xls";
int rownum = excelReader.getRowCount(path,"DataSet");
int colcount = excelReader.getCellCount(path,"DataSet",1);
String logindata[][]=new String[rownum][colcount];
for (int i=1;i<=rownum;i++){
for (int j=0;j<colcount;j++){
logindata[i-1][j]=excelReader.getCellData(path,"DataSet",i,j);
}
}
return logindata;
}
}
exception below:
java.lang.NullPointerException
at com.insurance.testCases.TC_LoginDdt_002.loginDDT(TC_LoginDdt_002.java:17)
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: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 com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:109)
base class:
package com.insurance.testCases;
import com.insurance.utilities.Log;
import com.insurance.utilities.readConfig;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.annotations.Parameters;
import java.util.concurrent.TimeUnit;
public class baseClass {
readConfig readconfig = new readConfig();
public String baseUrl = readconfig.getApplicationUrl();
public String username = readconfig.getUsername();
public String password = readconfig.getPassword();
public static WebDriver driver;
public static Logger logger;
#Parameters("browser")
#Before
public void SetUp(){
Log.startLog("Test is Starting");
logger = Logger.getLogger("einsurance");
System.setProperty("webdriver.chrome.driver","Drivers/chromedriver.exe");
driver = new ChromeDriver();
//System.setProperty("webdriver.edge.driver","Drivers/msedgedriver.exe");
// driver = new EdgeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#After
public void tearDown(){
Log.endLog("Test is Ending!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
driver.quit();
}
public String randomestring(){
String generatedstring = RandomStringUtils.randomAlphanumeric(20);
return (generatedstring);
}
public static String randomeNum(){
String generatestring2 = RandomStringUtils.randomNumeric(8);
return (generatestring2);
}
}
The root cause of your problem is in your base class.
You are initialising/cleaning a WebDriver object via the Unit provided Before and After.
TestNG does not recognise JUnit setup and teardown annotations
To fix this problem, all you would need to do is to use
Instead of Before use org.testng.annotations.BeforeClass (or) BeforeMethod
Instead of After use org.testng.annotations.AfterClass (or) AfterMethod
I suspect your baseUrl seems to be empty based on NPE at line 17 of TC_LoginDdt_002. Run in Debug mode to ensure your public String baseUrl = readconfig.getApplicationUrl(); is actually retrieving and initializing the baseUrl to your desired URL
Related
I have a base class as follows where I load the property file and initialize browser
package com.mystore.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
//import org.apache.log4j.xml.DOMConfigurator;
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.PageFactory;
import org.testng.annotations.BeforeTest;
import io.github.bonigarcia.wdm.WebDriverManager;
import com.mystore.actiondriver.ActionDriver;
public class BaseClass1 {
public static Properties prop;
public static WebDriver driver;
//ActionDriver a = new ActionDriver();
#BeforeTest
public void loadConfig() {
try {
prop = new Properties();
System.out.println("super constructor invoked");
FileInputStream ip = new FileInputStream(
System.getProperty("user.dir") + "/Configuration/Config.properties");
prop.load(ip);
System.out.println("driver: "+ driver);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void launchApp() {
String browserName = prop.getProperty("browser");
if (browserName.equalsIgnoreCase("Chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
System.out.println("driver: "+ driver);
} else if (browserName.equalsIgnoreCase("FireFox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if (browserName.equalsIgnoreCase("IE")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
}
ActionDriver.implicitWait(driver, 10);
ActionDriver.pageLoadTimeOut(driver, 30);
driver.get(prop.getProperty("url"));
}
}
Index page class which inherits BaseClass and code below
package com.mystore.pageobjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.mystore.actiondriver.ActionDriver;
import com.mystore.base.BaseClass;
import com.mystore.base.BaseClass1;
public class IndexPage1 extends BaseClass1{
#FindBy(xpath = "//a[#class='login']")
WebElement signInBtn;
#FindBy(xpath = "//img[#class='logo img-responsive']")
WebElement myStoreLogo;
#FindBy(id="search_query_top")
WebElement searchProductBox;
#FindBy(name="submit_search")
WebElement searchButton;
public IndexPage1() {
PageFactory.initElements(driver, this);
}
public LoginPage clickOnSignIn() {
ActionDriver.click(driver,signInBtn);
return new LoginPage();
}
public boolean validateLogo() throws Throwable{
System.out.println("Inside Validate Logo");
return myStoreLogo.isDisplayed();
//return true;
//return ActionDriver.isDisplayed(driver, myStoreLogo);
}
public String getMyStoreTitle() {
String myStoreTitle = driver.getTitle();
return myStoreTitle;
}
public SearchResultPage searchProduct(String productName) throws InterruptedException {
Thread.sleep(10000);
searchProductBox.sendKeys(productName);
Thread.sleep(10000);
System.out.println("I passed!");
ActionDriver.type(searchProductBox, productName);
ActionDriver.implicitWait(driver, 60);
ActionDriver.click(driver, searchButton);
return new SearchResultPage();
}
}
IndexPageTest class with test - where I try to call verifyLogo() test which checks if webElement myStoreLogo is displayed and should return true but returns false and NPE .
package com.mystore.testcases;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.mystore.base.BaseClass;
import com.mystore.base.BaseClass1;
import com.mystore.pageobjects.IndexPage;
import com.mystore.pageobjects.IndexPage1;
public class IndexPageTest1 extends BaseClass1{
IndexPage1 indexPage1 = new IndexPage1();
#BeforeMethod
public void setup() {
launchApp();
}
//#AfterMethod
public void tearDown() {
driver.quit();
}
#Test()
public void verifyLogo() throws Throwable{
//indexPage1= new IndexPage();
boolean result=indexPage1.validateLogo();
System.out.println("The value of result is:"+ result);
Assert.assertTrue(result);
}
#Test(enabled = false)
public void verifySearchProduct() throws InterruptedException {
indexPage1.searchProduct("t-shirt");
}
#Test(enabled=false)
public void verifyTitle() {
String actTitle=indexPage1.getMyStoreTitle();
Assert.assertEquals(actTitle, "My Store");
}
}
Gives results below
driver: ChromeDriver: chrome on MAC (fa4c8f6fb20e625d6d7e2b148850b17b)
Inside Validate Logo
FAILED: verifyLogo
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.$Proxy12.isDisplayed(Unknown Source)
at com.mystore.pageobjects.IndexPage1.validateLogo(IndexPage1.java:47)
at com.mystore.testcases.IndexPageTest1.verifyLogo(IndexPageTest1.java:40)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:597)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:816)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.testng.TestRunner.privateRun(TestRunner.java:766)
at org.testng.TestRunner.run(TestRunner.java:587)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1109)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
Please help, I'm not sure why the webelement is not identified. I tried with other web elements and they also get the same NPE.
The problem lies in your test code.
The WebDriver object that is part of your base class BaseClass1 is getting initialised only when the method launchApp() is invoked.
But the constructor of your page class IndexPage1 already tries to access the WebDriver object (which at the time of instantiation of IndexPage1 is null)
So you end up invoking PageFactory.initElements(driver, this); with a null value for driver
Solution.
Please remove the logic of managing your webdriver instances via your base class and segregate it to a separate utility method which when called can give you a WebDriver object. Alternatively you can also make use of a library such as Autospawn that I created which uses an annotation way of managing webdriver instances. - The documentation should explain how to use this library. Note that if you use this library, you would need to create all your page classes within your #Test method (because that's the only place wherein a valid WebDriver instance would be available in the current Thread's context)
Refactor your IndexPage1 class's constructor so that it accepts a WebDriver instance as a parameter from outside.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
It works fine when I run the test class by using the all objects form PartnerLogin POM class to Test1 Class. The problem goes when I try to call login.Login(); which contains all the objects form PartnerLogin POM class method (from another class) and calling profile object right after, getting to the null pointer exception error:
java.lang.NullPointerException at page
object.PartnerNavigationDrawer.Profile(PartnerNavigationDrawer.java:30)
How can I solve this?
POM class
package pageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class PartnerNavigationDrawer {
public WebDriver driver;
public PartnerNavigationDrawer(WebDriver driver) {
// TODO Auto-generated constructor stub
this.driver = driver;
}
By Dashboard = By.cssSelector("a[href='partner_dashboard.php']");
By Profile = By.cssSelector("a[href='partner_page.php']");
public WebElement Dashboard() {
return driver.findElement(Dashboard);
}
public WebElement Profile() {
return driver.findElement(Profile);
}
}
Test Class
package com.rslsolution;
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.testng.annotations.Test;
import mainTest.PartnerLoginTest;
import com.rslsolution.Base;
import pageObject.PartnerLogin;
import pageObject.PartnerNavigationDrawer;
public class Test1 extends Base{
String baseUrl = System.getProperty("user.dir");
Properties pro = new Properties();
FileInputStream fis;
WebDriver driver;
#Test
public void testMethod() throws InterruptedException, IOException
{
fis =new FileInputStream(baseUrl+"\\DataDriven\\DataDriven.properties");
pro.load(fis);
// driver = initializeBrowser();
// driver.get(pro.getProperty("appUrl"));
PartnerLoginTest partnerLogin=new PartnerLoginTest();
Thread.sleep(3000);
partnerLogin.Login();
Thread.sleep(3000);
// PartnerLogin login=new PartnerLogin(driver);
// Thread.sleep(3000);
// login.Partner_Login().click();
// Thread.sleep(3000);
// login.email().sendKeys(pro.getProperty("userName"));
// login.password().sendKeys(pro.getProperty("partnerPassword"));
// login.Login_Button().click();
PartnerNavigationDrawer navigationDrawer = new PartnerNavigationDrawer(driver);
navigationDrawer.Profile().click();
System.out.println("Checking git push command");
}
}
Error Log
java.lang.NullPointerException
at pageObject.PartnerNavigationDrawer.Profile(PartnerNavigationDrawer.java:28)
at com.rslsolution.Test1.testMethod(Test1.java:35)
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:669)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:877)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1201)
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:776)
at org.testng.TestRunner.run(TestRunner.java:634)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:425)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:420)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:385)
at org.testng.SuiteRunner.run(SuiteRunner.java:334)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1318)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1243)
at org.testng.TestNG.runSuites(TestNG.java:1161)
at org.testng.TestNG.run(TestNG.java:1129)
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)
PartnerLogin Class
package pageObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class PartnerLogin {
WebDriver driver;
public PartnerLogin(WebDriver driver) {
this.driver = driver;
}
By Partner_Login = By.xpath("/html/body/div[3]/p/a[3]/b/span");
By email = By.cssSelector("input[id='userName']");
By password = By.cssSelector("input[id='pass']");
By Login_Button = By.cssSelector("button[id='submit']");
public WebElement Partner_Login() {
return driver.findElement(Partner_Login);
}
public WebElement email() {
return driver.findElement(email);
}
public WebElement password() {
return driver.findElement(password);
}
public WebElement Login_Button() {
return driver.findElement(Login_Button);
}
}
driver is null in class Test1. I cannot see where you assign a value to it.
package utils;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import java.util.concurrent.TimeUnit;
public class BrowserUtils {
public WebDriver driver = null;
#BeforeTest
public void setUp(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\sdad\\Downloads\\Softwares\\BrowserDrivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().setPosition(new Point(0, 0));
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
#AfterTest
public void tearDown(){
driver.close();
driver.quit();
}
}
package parallel_3;
import org.testng.Assert;
import org.testng.annotations.Test;
import parallel_2.Headers;
import parallel_2.Images;
import parallel_2.Styles;
import utils.BrowserUtils;
public class Test_01 extends BrowserUtils {
Headers headers;
Images images;
Styles styles;
private final String HEADER_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Headers.html",
IMAGES_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Images.html";
#Test
public void test(){
driver.get(HEADER_FILE_PATH);
headers = new Headers(driver);
Assert.assertEquals(driver.getTitle(), "Headers");
Assert.assertEquals(headers.header4.getText(), "This is Header 4");
headers.images_link.click();
images = new Images(driver);
Assert.assertEquals(driver.getTitle(), "Images");
Assert.assertEquals(images.header2.getText(), "Image with width and height");
images.styles_link.click();
styles = new Styles(driver);
Assert.assertEquals(driver.getTitle(), "Page Styles");
Assert.assertEquals(styles.paragraph.getText(), "This is a paragraph");
styles.images_link.click();
}
}
package parallel_3;
import org.testng.Assert;
import org.testng.annotations.Test;
import parallel_2.Headers;
import parallel_2.Images;
import parallel_2.Styles;
import utils.BrowserUtils;
public class Test_02 extends BrowserUtils {
Headers headers;
Images images;
Styles styles;
private final String HEADER_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Headers.html",
IMAGES_FILE_PATH ="C:\\Users\\sdad\\Downloads\\Projects\\Demo-Website\\Images.html";
#Test
public void test(){
driver.get(IMAGES_FILE_PATH);
images = new Images(driver);
Assert.assertEquals(driver.getTitle(), "Images");
Assert.assertEquals(images.header2.getText(), "Image with width and height");
images.styles_link.click();
styles = new Styles(driver);
Assert.assertEquals(driver.getTitle(), "Page Styles");
Assert.assertEquals(styles.paragraph.getText(), "This is a paragraph");
styles.images_link.click();
headers = new Headers(driver);
Assert.assertEquals(driver.getTitle(), "Headers");
Assert.assertEquals(headers.header4.getText(), "This is Header 4");
headers.images_link.click();
}
}
Error message
java.lang.NullPointerException
at parallel_3.Test_01.test(Test_01.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: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 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
#BeforeTest doesn't run for all the #Test, only before the first one, so driver is never initialized. From testng docs
#BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
You can use #BeforeMethod annotation for that
#BeforeMethod: The annotated method will be run before each test method.
Same goes for #AfterTest and #AfterMethod.
I have created Page Object Model for the selemium testcases. I have defined a login method in 'LoginPage' class and some methods in 'CommonMethods' class. Now when I run the test, it shows NullPointerException error. I did the same thing with JUnit and it worked fine with this setup but not working with TestNG.
This is my Page Object file:
package pages;
import org.openqa.selenium.WebDriver;
public class PageObject {
public WebDriver driver;
public PageObject(WebDriver driver) {
this.driver=driver;
}
}
CommonMethods file
package 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 CommonMethods extends PageObject {
public CommonMethods(WebDriver driver) {
super(driver);
}
public By ByLocator(String locator) {
By result=null;
if(locator.startsWith("/")||locator.startsWith("//"))
result=By.xpath(locator);
else if(locator.startsWith(".")||locator.startsWith("#"))
result=By.cssSelector(locator);
return result;
}
public void waitForElementPresent(By locator, int time) {
WebDriverWait wait = new WebDriverWait(driver, time);
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
}
}
LoginPage file
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage extends PageObject {
public LoginPage(WebDriver driver) {
super(driver);
}
CommonMethods cm = new CommonMethods(driver);
By usernameField = cm.ByLocator("#login");
By passwordField = cm.ByLocator("#password");
By submitButton = cm.ByLocator("#signin_submit");
public void loginWithCustomer() {
driver.get("https://www.stg.keepcollective.com/signin");
//cm.waitForElementPresent(usernameField, 3000);
driver.findElement(usernameField).sendKeys("joshimeghakeep#yopmail.com");
driver.findElement(passwordField).sendKeys("111111");
}
}
Test file
package tests;
import org.testng.annotations.Test;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import java.io.*;
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.testng.ITestResult;
import org.testng.annotations.AfterClass;
import pages.*;
public class LoginCheck {
public WebDriver driver;
CommonMethods cm=new CommonMethods(driver);
LoginPage lp=new LoginPage(driver);
#BeforeClass
public void beforeClass() throws Exception {
System.setProperty("webdriver.chrome.driver", "/home/himanshu/Downloads/chromedriver_linux64/chromedriver");
driver= new ChromeDriver();
}
#Test
public void checkLoginFunctionality() {
lp.loginWithCustomer();
}
#AfterMethod
public void Screenshot(ITestResult result) throws IOException {
if(result.getStatus()==ITestResult.FAILURE) {
TakesScreenshot ss= (TakesScreenshot)driver;
File screenshotfile = ss.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotfile, new File("./Screenshots/"+result.getName()+".png"));
}
}
#AfterClass
public void afterClass() {
driver.close();
}
}
I am getting this error:
FAILED: checkLoginFunctionality
java.lang.NullPointerException
at pages.LoginPage.loginWithCustomer(LoginPage.java:19)
at tests.LoginCheck.checkLoginFunctionality(LoginCheck.java:35)
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: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:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Move the initialization of CommonMethods cm and LoginPage lp in the beforeClass() method and put it after the creation of ChromeDriver. The #BeforeClass doesn't mean that this method will be executed before the initialization of the LoginCheck class. What it means is that this is method will be executed before any other methods in this class is executed.
public class LoginCheck {
public WebDriver driver;
private CommonMethods cm;
private LoginPage lp;
#BeforeClass
public void beforeClass() throws Exception {
System.setProperty("webdriver.chrome.driver", "/home/himanshu/Downloads/chromedriver_linux64/chromedriver");
driver= new ChromeDriver();
cm = new CommonMethods(driver);
lp = new LoginPage(driver);
}
#Test
public void checkLoginFunctionality() {
lp.loginWithCustomer();
}
#AfterMethod
public void Screenshot(ITestResult result) throws IOException {
if(result.getStatus()==ITestResult.FAILURE) {
TakesScreenshot ss= (TakesScreenshot)driver;
File screenshotfile = ss.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotfile, new File("./Screenshots/"+result.getName()+".png"));
}
}
#AfterClass
public void afterClass() {
driver.close();
}
}
I am trying to test the login function to Gmail. But it displays an exception error "java.lang.NullPointerException" . Code as follows:
package gmail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class Gmail {
WebDriver driver;
#Before
public void setup() {
System.setProperty("webdriver.chrome.driver","E://chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://accounts.google.com/");
driver.manage().timeouts().implicitlyWait(300, TimeUnit.SECONDS);
}
#After
public void quit() {
driver.manage().deleteAllCookies();
driver.quit();
}
#Test()
public void login() {
WebElement txtUserName=driver.findElement(By.name("Email"));
txtUserName.sendKeys("abc#gmail.com");
WebElement txtPassword=driver.findElement(By.name("Passwd"));
txtPassword.sendKeys("abcd123");
WebElement btnLogin=driver.findElement(By.name ("signIn"));
btnLogin.submit();
}
}
Error:
FAILED: login
java.lang.NullPointerException
at gmail.Gmail.login(Gmail.java:33)
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:84)
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:335)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:330)
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:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
Your test annotations does not belongs to TestNG.
Replace
#Before with #BeforeTest
#After with #AfterTest
#Test should point TestNG library
In this code snippet #Test annotation belongs to TestNg framework and #Before, #After annotation belongs to Junit framework. Eclipse will show run as TestNG test(since Test annotation is imported from TestNG library) if you run it as TestNG it wont execute #Before and #After(since they belong to Junit framework) therefore driver variable is not initialized so we are getting NullPointer Exception
Either we should import Junit Test annotation and run as Junit test or change #After & #Before to #AfterTest & #BeforeTest and run as TestNG test
package selenium;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertEquals;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class Aply_login {
WebDriver d;
private By by;
#Test
public void aplylogin () throws BiffException, IOException, InterruptedException{
d.get("http://multishop.orderzen.com/customer/account/login/");
assertEquals("Customer Login | Multishop",d.getTitle());
File f = new File("F:\\workspace locaiton\\page object model\\aplyinputs.xls");
Workbook w = Workbook.getWorkbook(f);
Sheet s = w.getSheet("Sheet1");
for(int i=0;i<s.getRows();i++) {
//User name
d.findElement(By.id("email")).clear();
d.findElement(By.id("email")).sendKeys(s.getCell(0,i).getContents());
String uname = d.findElement(By.id("email")).getAttribute("value");
//Password
d.findElement(By.id("pass")).clear();
d.findElement(By.id("pass")).sendKeys(s.getCell(1,i).getContents());
String pass = d.findElement(By.id("pass")).getAttribute("value");
//submit
d.findElement(By.id("send2")).click();
//Blank user name and blank password (1)
if (uname.equals("") && pass.equals("")) {
d.findElement(By.id("advice-required-entry-email"));
d.findElement(By.id("advice-required-entry-pass"));
Thread.sleep(6000);enter code here
}
//Blank user name and valid/invalid password (2)
else if(uname.equals("")){
d.findElement(By.id("advice-required-entry-email"));
Thread.sleep(6000);
}
//invalid user name blank password (3)
else if(isElementPresent(d,By.xpath(".//*[#id='advice-validate-email-email']"),By.xpath(".//*[#id='advice-required-entry-pass']")))
{
d.findElement(By.xpath(".//*[#id='advice-validate-email-email']"));
d.findElement(By.xpath(".//*[#id='advice-required-entry-pass']"));
Thread.sleep(6000);
}
//valid user name & password (4)
else if(isElementPresent(d,By.linkText("Log Out"))) {
d.findElement(By.linkText("Log Out")).click();
Thread.sleep(6000);
}
//Invalid user & password (5)
else if(isElementPresent(d,By.id("advice-validate-email-email"),By.id("advice-validate-password-pass"))) {
d.findElement(By.id("advice-validate-email-email"));
d.findElement(By.id("advice-validate-password-pass"));
Thread.sleep(6000);
}
else if(isElementPresent(d,By.cssSelector("span..firepath-matching-node"))) {
d.findElement(By.cssSelector("span..firepath-matching-node"));
}
}
}
private boolean isElementPresent(WebDriver d2, By linkText) {
d.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
try{
d.findElement(by);
return true;
}
catch(NoSuchElementException e) {
return false;
}
}
private boolean isElementPresent(WebDriver d2, By xpath, By xpath2) {
d.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
try {
d.findElement(by);
return true;
}
catch(NoSuchElementException e){
return false;
}
}
#BeforeMethod
public void setUp()
{
// Launch browser
d=new FirefoxDriver();
//System.setProperty("webdriver.chrome.driver","F:\\lib\\chromedriver.exe");
//d =new ChromeDriver();
// Maximize window
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
}
#AfterMethod
public void tearDown()
{
// Close browser
d.quit();
}
}
Always check the import statements that you are using in your code, make sure it is always the one from desired library. There can be cases where same method exits in multiple classes from different library.
Here you are using import statements of JUnit instead of TestNg.
Solution:-
Use TestNG import statements.
Use #AfterTest instead of #After annotation.
Use #BeforeTest instead of #Before annotation.
It should help!