org.testng.TestNGException : Cannot instantiate class - java

I am facing this 'Cannot insantiate class' error on running one of my test cases in selenium webdriver using java(Using Maven project).
Below is the parent class where I defined driver and properties
package com.pvi.qa.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestBase {
public static WebDriver driver;
public static Properties prop ;
public TestBase() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("C:\\Users\\RxLogix\\eclipse-workspace\\PviIntake\\src\\main\\java\\com\\pvi\\qa\\config\\config.properties"));
prop.load(ip);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void initialization () {
String BrowserName = prop.getProperty("browser");
if(BrowserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32 (1)\\chromedriver.exe");
driver = new ChromeDriver();}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
}
Below is the test cases class which I am running through TestNG
package com.pvi.qa.testcases;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.pvi.qa.base.TestBase;
import com.pvi.qa.pages.HomePage;
import com.pvi.qa.pages.LoginPage;
public class LoginPageTest extends TestBase{
LoginPage loginPage;
HomePage homePage;
public LoginPageTest() {
super();
}
#BeforeMethod
public void setUp() {
initialization();
loginPage = new LoginPage();
}
#Test
public void logintest() {
homePage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
And below is the error I am getting -
[RemoteTestNG] detected TestNG version 6.14.3
org.testng.TestNGException:
Cannot instantiate class com.pvi.qa.testcases.LoginPageTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:423)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:336)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:125)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:190)
at org.testng.TestClass.getInstances(TestClass.java:95)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:81)
at org.testng.TestClass.init(TestClass.java:73)
at org.testng.TestClass.<init>(TestClass.java:38)
at org.testng.TestRunner.initMethods(TestRunner.java:389)
at org.testng.TestRunner.init(TestRunner.java:271)
at org.testng.TestRunner.init(TestRunner.java:241)
at org.testng.TestRunner.<init>(TestRunner.java:192)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:713)
at org.testng.SuiteRunner.init(SuiteRunner.java:260)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:198)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1295)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1273)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1128)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:24)
... 25 more
Caused by: java.lang.NullPointerException
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at com.pvi.qa.base.TestBase.<init>(TestBase.java:20)
at com.pvi.qa.testcases.LoginPageTest.<init>(LoginPageTest.java:17)
... 30 more
I have tried everything but not worked for me, Please let me know why I am getting this error. Thanks

The lowest 'caused by' section points you to the underlying exception in your base class constructor: you are calling System.getProperty with a file path; that will probably return null. To me it looks like the whole call shouldn't be there, and you just want to pass the file path to the FileInputStream constructor (or read it from a system property with some key)

Looking at the code, I understand the issue is in the constructor of the base class.
LoginPageTest calls super() which invokes TestBase.
FileInputStream needs a file path. I suspect FileInputSteam object created is coming as null.
Why are you calling System.getProperty? Is the config.properties file available?

Just Remove System.getproperty from your base class. Use this lines of code
prop = new Properties();
FileInputStream ip = new FileInputStream(("C:\\Users\\RxLogix\\eclipse-workspace\\PviIntake\\src\\main\\java\\com\\pvi\\qa\\config\\config.properties"));
prop.load(ip);

Related

I am getting NPE when i try to validate a webElement using isDisplayed method. I am unable to access any webelement and action on it

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.

DataProvider using TestNG,Java and InteliJ Idea

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

Geting java.lang.NullPointerException at pageObject.PartnerNavigationDrawer.Profile(PartnerNavigationDrawer.java:30) when I call method [duplicate]

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.

TestNG with IE webdriver

Hi Im a newbie to selenium, i was trying to use TestNG with IE webdriver, Now i cant instantiate the IE driver directly under the class (Not the main method). When i do that i get the below error:
Multiple markers at this line
- Syntax error on tokens, FormalParameter expected instead
- Syntax error on token(s), misplaced construct(s)
- Syntax error on token ""webdriver.ie.driver"", invalid
If i then put on a method with #BeforeSuite annotation, i need to pass the driver to every other test method in the class. Is there a way where i can by pass this passing the driver object.
Find below the sample code i am using:
package FirstTestNGPackage;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class FirstTestNGclass {
#BeforeSuite
public void SetDriverPaths()
{
File IEDriver = new File("C:\\Users\\REDACTED\\Desktop\\SeleniumJars\\IE Driver\\IEDriverServerX64_2.44.0.exe");
System.setProperty("webdriver.ie.driver", IEDriver.getAbsolutePath());
WebDriver Driver = new InternetExplorerDriver();
}
#Test
public void tester()
{
Driver.findElement(By.id("keywordInput")).sendKeys("REDACTED");
Driver.findElement(By.id("keywordInput")).sendKeys(Keys.ENTER);
Assert.assertEquals(Driver.findElement(By.xpath(".//*[#id='search_results']/h1/span/strong")).getText(), "REDACTED");
}
#BeforeTest
public void RMSLogin()
{
Driver.navigate().to("REDACTED");
}
#AfterTest
public void closeBrowser()
{
Driver.quit();
}
}
init you webdriver like this then you can use it in every method with this.driver.
public class FirstTestNGclass {
public WebDriver driver;
#BeforeSuite
public void SetDriverPaths()
{
// ....
this.driver = new InternetExplorerDriver();
}
// ....
}
One of the simple solution to this problem is to use a common driver class for your Test suite...so that we can use the same driver instance in all classes
Common driver class
public class Driver {
public static WebDriver driver=null;
public static WebDriver startdriver(String browser){
if(browser.equalsIgnoreCase("Chrome")){
System.setProperty("webdriver.chrome.driver", "path");
driver=new ChromeDriver();
}else if(browser.equals("IE")){
System.setProperty("webdriver.ie.driver", IEDriver.getAbsolutePath());
driver=new InternetExplorerDriver();
}
return driver;
}
}
you can create a driver instance like this
Driver.startdriver("IE");
You can use the driver object like classname.instance
Driver.driver.findElement(By.xpath("path"));
Hope this helps you...if you have any queries Kindly get back

Selenium TestNG - java.lang.NullPointerException

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!

Categories

Resources