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!
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.
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
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.
.clear() in my test script is not working with testng version 6.14.2 but when i am running the same code without testng the clear method is working as expected.
i am running the code as mentioned below:
driver.findElement(By.id("email")).clear();
But this loc is not performing any action.
Blockquote
clear() is working for me. refer the following snippet
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Testngexample {
private WebDriver driver;
#BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver","Add chromedriver path chromedriver.exe");
driver = new ChromeDriver();
}
#AfterClass
public void tearDown() {
driver.quit();
}
#Test
public void GoogleEarch() throws InterruptedException {
driver.get("https://www.google.com/");
driver.manage().window().maximize();
driver.findElement(By.name("q")).click();
driver.findElement(By.name("q")).sendKeys("testing");
Thread.sleep(5000);
driver.findElement(By.name("q")).clear();
Thread.sleep(5000);
driver.close();
}
}
I'm using Selenium and TestNG for the first time and I've been trying to search an element by its ID but I keep getting an "Cannot instantiate class" error. This is my code:
import org.testng.annotations.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
public class NewTesting {
WebDriver driver = new FirefoxDriver();
#BeforeTest
public void setUp() {
driver.get("http://book.theautomatedtester.co.uk/chapter1");
}
#AfterTest
public void tearDown() {
driver.quit();
}
#Test
public void testExample() {
WebElement element = driver.findElement(By.id("verifybutton"));
}
}
Maybe I missed installing something? I installed the TestNG plug-in for eclipse and added the WebDriver JAR files, do I need to do more?
I tried following multiple tutorials but I keep getting errors, I hope someone can help. Thanks in advance!
EDIT:
I now have this:
public class NewTest {
private WebDriver driver;
#BeforeTest
public void setUp() {
System.setProperty("webdriver.gecko.driver","C:\\Program Files\\Selenium\\FirefoxDriver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://book.theautomatedtester.co.uk/chapter1");
}
#AfterTest
public void tearDown() {
driver.quit();
}
#Test
public void testExample() {
WebElement element = driver.findElement(By.id("verifybutton"));
}
}
It does open the website now but I'm getting a nullpointer exception now:
FAILED CONFIGURATION: #AfterTest tearDown
java.lang.NullPointerException
at NewTest.tearDown(NewTest.java:21)
Replace this set of imports:
import org.testng.annotations.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;
With:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
Additionally, you have to download the required format of GeckoDriver executable from mozilla/geckodriver, extract the binary and then initialize the FirefoxDriver.
Your effective code block will be:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.annotations.AfterTest;
public class NewTesting {
WebDriver driver;
#BeforeTest
public void setUp() {
System.setProperty("webdriver.gecko.driver","C:\\path\\to\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get("http://book.theautomatedtester.co.uk/chapter1");
}
#AfterTest
public void tearDown() {
driver.quit();
}
#Test
public void testExample() {
WebElement element = driver.findElement(By.id("verifybutton"));
}
}
If you're on windows, this previous question may be some help to you.
It mentions that you can download geckodriver, and then initialize your FirefoxDriver like this:
System.setProperty("webdriver.gecko.driver","G:\\Selenium\\Firefox driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();