You need to initialize your WebDriver first. As I seeing you are creating the reference of WebDriver but not initialized, try as below :-
WebDriver driver = new ChromeDriver(); //or other driver which you want
Note :- If you want to initialize ChromeDriver you need to download chromedriver and set system property before initialize driver as :-
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
So details answer like as below :-
public class VendorsHomePageTest
{
public WebDriver driver;
@Test
public void verifyVendorsHomePageTest() throws Exception
{
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver(); //or other driver which you want
LoginIntoVendors login=PageFactory.initElements(driver, LoginIntoVendors.class);
login.verifyLoginVendors();
VendorsHomePageApp vhpapp= PageFactory.initElements(driver, VendorsHomePageApp.class);
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(3000);
vhpapp.clickOnNotificationsTab();
vhpapp.clickOnProfileTab();
vhpapp.clickOnTendersTab();
vhpapp.clickOnDashboardTab();
vhpapp.clickOnFirstTender();
}
}
Edited :- You need to create separate class which gives you WebDriver instance as below :-
public class DriverInit {
public WebDriver driver;
private static DriverInit driverInit = null;
public static DriverInit getInstance() {
if (driverInit == null) {
driverInit = new DriverInit();
}
return driverInit;
}
private DriverInit() {
this.driver = new FirefoxDriver();
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
this.driver.get("******");
}
public WebDriver getDriver() {
return this.driver;
}
now you can call it into LoginIntoVendors as below :-
public class LoginIntoVendors
{
@Test
public void verifyLoginVendors() throws Exception
{
WebDriver driver = DriverInit.getInstance().getDriver();
IntiationPage vendorInit=PageFactory.initElements(driver, IntiationPage.class);
vendorInit.clickOnLoginButton();
VendorsLoginAction Loginven=PageFactory.initElements(driver, VendorsLoginAction.class);
Loginven.vendorlogin("***","***@gmail.com", "****");
String title = driver.getTitle();
System.out.println("Title is :" + title );
}
}
and in the VendorsHomePageTest as below :-
public class VendorsHomePageTest
{
public WebDriver driver;
@Test
public void verifyVendorsHomePageTest() throws Exception
{
driver = DriverInit.getInstance().getDriver();
LoginIntoVendors login=PageFactory.initElements(driver, LoginIntoVendors.class);
login.verifyLoginVendors();
VendorsHomePageApp vhpapp= PageFactory.initElements(driver, VendorsHomePageApp.class);
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(3000);
vhpapp.clickOnNotificationsTab();
vhpapp.clickOnProfileTab();
vhpapp.clickOnTendersTab();
vhpapp.clickOnDashboardTab();
vhpapp.clickOnFirstTender();
}
}
Hope it helps..:)
Answer from Saurabh Gaur on Stack OverflowYou need to initialize your WebDriver first. As I seeing you are creating the reference of WebDriver but not initialized, try as below :-
WebDriver driver = new ChromeDriver(); //or other driver which you want
Note :- If you want to initialize ChromeDriver you need to download chromedriver and set system property before initialize driver as :-
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
So details answer like as below :-
public class VendorsHomePageTest
{
public WebDriver driver;
@Test
public void verifyVendorsHomePageTest() throws Exception
{
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver(); //or other driver which you want
LoginIntoVendors login=PageFactory.initElements(driver, LoginIntoVendors.class);
login.verifyLoginVendors();
VendorsHomePageApp vhpapp= PageFactory.initElements(driver, VendorsHomePageApp.class);
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(3000);
vhpapp.clickOnNotificationsTab();
vhpapp.clickOnProfileTab();
vhpapp.clickOnTendersTab();
vhpapp.clickOnDashboardTab();
vhpapp.clickOnFirstTender();
}
}
Edited :- You need to create separate class which gives you WebDriver instance as below :-
public class DriverInit {
public WebDriver driver;
private static DriverInit driverInit = null;
public static DriverInit getInstance() {
if (driverInit == null) {
driverInit = new DriverInit();
}
return driverInit;
}
private DriverInit() {
this.driver = new FirefoxDriver();
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
this.driver.get("******");
}
public WebDriver getDriver() {
return this.driver;
}
now you can call it into LoginIntoVendors as below :-
public class LoginIntoVendors
{
@Test
public void verifyLoginVendors() throws Exception
{
WebDriver driver = DriverInit.getInstance().getDriver();
IntiationPage vendorInit=PageFactory.initElements(driver, IntiationPage.class);
vendorInit.clickOnLoginButton();
VendorsLoginAction Loginven=PageFactory.initElements(driver, VendorsLoginAction.class);
Loginven.vendorlogin("***","***@gmail.com", "****");
String title = driver.getTitle();
System.out.println("Title is :" + title );
}
}
and in the VendorsHomePageTest as below :-
public class VendorsHomePageTest
{
public WebDriver driver;
@Test
public void verifyVendorsHomePageTest() throws Exception
{
driver = DriverInit.getInstance().getDriver();
LoginIntoVendors login=PageFactory.initElements(driver, LoginIntoVendors.class);
login.verifyLoginVendors();
VendorsHomePageApp vhpapp= PageFactory.initElements(driver, VendorsHomePageApp.class);
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(3000);
vhpapp.clickOnNotificationsTab();
vhpapp.clickOnProfileTab();
vhpapp.clickOnTendersTab();
vhpapp.clickOnDashboardTab();
vhpapp.clickOnFirstTender();
}
}
Hope it helps..:)
Your driver seems to be null what you can do to avoid this situation is to instantiate your driver reference.
In your test class you can instantiate your driver.
public class VendorsHomePageTest {
public WebDriver driver;
@Test
public void verifyVendorsHomePageTest() throws Exception {
driver = new FirefoxDriver(); // or whatever browser you want.
// Here you can initialise the elements in `PageObject` class.
VendorsHomePageApp vhpapp= PageFactory.initElements(driver, VendorsHomePageApp.class);
// Rest of your code
}
}
According to WebDriver API JavaDoc, if no matching elements are found then the NoSuchElementException is thrown by findElement() method, not NullPointerException. So the root cause of your problem is not a wrong XPath expression.
Instead, your stacktrace and your source code suggests this is a problem with driver variable not initialized: you try to call findElement() method on a null object.
One way to confirm that is to print the driver value:
System.out.println("driver=" + driver);
just before the exception is thrown, i.e., before line 31 of the SMBSignupLandingPage class. Or simply run the application in debug mode, put breakpoint in same line and evaluate the value of the variable.
yo inicialicé la variable en los metodos
(approx. translation: I would initialize the variable with a method like this)
try {
driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps);
}
catch (MalformedURLException e) {
}
Here
public WebDriver driver;
LoginPage lp = new LoginPage(driver);
You pass null to the constructor because driver field yet not initialized. The fact you later assign some non-null value to the field does not automatically rewrite reference in LoginPage. Hence you get NPE when access to that null field.
As Alexey said, the problem is that you are passing a null to the creation of LoginPage.
public WebDriver driver;
LoginPage lp = new LoginPage(driver);
What you can do is to set up a LoginPage for each test:
@BeforeEach
public void setUp() {
driver = initializeDriver();
lp = new LoginPage(driver);
}
If you prefer to set it up only once for all tests in the class, you can use the annotation @BeforeClass.
It looks like your code didn't init WebDriver and try to use it, so it throws the NullPointerException.
In TestNG, you can use @BeforeSuite, @BeforeTest, @BeforeClass to initialize your dependencies. The example below shows how to init the webdriver in 'BeforeClass'.
import Initiate.NewBOM;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
public class CreateBOM {
public WebDriver driver;
private NewBOM objNewBOM;
@BeforeClass
public void setupClass(){
driver = new FirefoxDriver();
}
@Test(priority = 1)
public void clickOnNewBOMButton(){
objNewBOM = new NewBOM(driver);
objNewBOM.CreateNewBOM();
}
}
Please Check your driver initiated, In case if driver is initiated two times so you may get the error where as second driver initiated . Eg. Actions act= new Actions(driver);
Initialisers are invoked before constructors and hence, NullPointerException, try the below code:
public class BaseClass{
public static WebDriver driver;
public BaseClass(WebDriver _driver){
driver = _driver;
FirstName = driver.findElement(By.name("firstname"));
LastName = driver.findElement(By.name("LastName"));
}
public WebElement FirstName;
public WebElement LastName;
//Rest of the code
@DarshanMehta has well explained the problem and its solution. I have just tested it and it works. I would also add:
The problem you are facing has been well discussed in Stackoverflow. I think this link can give you a better understanding of the order of execution when a class is instanciated: Are fields initialized before constructor code is run in Java?
Thus you can read in the first answer that initialization block is done after the super() part of the constructor, BUT before the rest of the constructor.
you would not have had this error if, for exemple, your driver was initialised in a superclass of BaseClass. Therefore, if you really want to initialized FirstNameand LastName in initialization block, you can create a superclass from which BaseTest will inherits. And it should solve your issue.
you can try the following code, that illustrates it: create a super class:
public class MotherClass {
public MotherClass(WebDriver _driver){
driver = _driver;
}
WebDriver driver;
}
and add super in the constructor of BaseClass, that inherits from MotherClass:
public class Testasupp extends MotherClass{
public BaseClass(WebDriver _driver)
{
super(_driver);
FirstName = driver.findElement(By.name("firstname"));
LastName = driver.findElement(By.name("LastName"));
}
To conclude: Except if you have good reason to prefer this solution, I really think @DashanMehta gives a better solution.
U are getting NPE(Null pointer exception) on line
loginButton.click();
it means you are doing some operation on object which got a null value and in this case it is none other than your loginButton
now the question comes up, Why login button is null when you are initialising it with
@FindBy(className = "ico fa fa-lock")
static WebElement loginButton;
it is possible because of web driver is not able to find this element and hence it is null
try following suggestions
public HomePage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
and if this does not work try with single class name like this
@FindBy(className = "ico")
private WebElement loginButton;
@FindBy(className = "login")
List<WebElement> buttons;
and while clicking like this
buttons.get(0).click();
else try with javascript click direct, it should surely work
((JavascriptExecutor)driver).executeScript("document.getElementsByClassName('login')[0].click()");
Please check line number 55 in HomePage.java
It says
loginButton.click();
Nullpointer is because loginButton is null, probably because it is not initialized.
Most probably because it is not able to find the element by the classes that you have mentioned.
You might want to use '.' in front of the class names
The problem seems to be in the declaration and usage of the variable driver. Although there is a class-scope variable driver, the Login() method stores the created WebDriver object in a method-scope variable. This means, that the class-scope variable driver is never set, resulting in NullPointerException when it is referenced.
To fix this, change the beginning of the Login() method:
//Launch Browser
driver = new ChromeDriver();
this worked for me too i declared driver outside of the method and again in method that why it through me nullpointer exception after removing duplicate element it worked for me.
package TestNGPackage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class BasicTestNG {
WebDriver driver;
@BeforeMethod
public void setup() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "Tools/chromedriver.exe"); driver= new ChromeDriver(); driver.get("https://www.google.com/"); Thread.sleep(1000); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); }
@Test
public void mytest()
{
String S1= driver.getTitle();
System.out.println("Title of page"+ S1);
}
@AfterMethod
public void teardown()
{
driver.close();;
//driver.manage().deleteAllCookies();
}
}
You get this error only because of using driver before creating an instance of it. Let's suppose you want to run this test case on Chrome and your PageObject class doesn't have Chrome Driver instance (if yes it will create new chrome driver instance again which is not supposed to do)
WebDriver driver;
public Alert waitingForAlert() throws InterruptedException {
Alert al = driver.switchTo().alert();
return al;
}
The nullPointer exception comes from this line: driver.switchTo().alert();
in order to use driver you should create an instance of it. Meaning you can do it by typing:
class BasePage extends PageObject {
@Managed
WebDriver driver;
public void setDriver()
{
System.setProperty("webdriver.chrome.driver","<Path of ChromeDriver.exe here>");
driver = new ChromeDriver(); // Creating new 'ChromeDriver' instance
}
public Alert waitingForAlert() throws InterruptedException {
setDriver();
Alert al = driver.switchTo().alert();
return al;
}
}
What you're seeing is that driver is still null because BasePage has not yet been instantiated. You will have to override the navigateTo method in some way to create a driver.
class BasePage extends PageObject {
@Managed
WebDriver driver;
public Alert waitingForAlert() throws InterruptedException {
Alert al = driver.switchTo().alert();
return al;
}
public void navigateTo() { // your code here ... }
}
You forgot to instantiate elements of your page.
PageFactory.initElements(...)
Refer to this question to get the details: How to Implement Page Object and Page Factory Pattern in Selenium Webdriver?. Since your fields are not instantiated, they are not deployed in memory, so when you are trying to access method of not existing object in
emails.sendKeys("sbhuvani661");
you get NullPointerException
I imagine it is null because it is not successfully finding the element in question. Look to make sure that your @FindBy annotation is correct for WebElement emails.
As I understood, you are trying to read each row's data from the excel file and passing them to
runTest(row.getCell(1).toString(),row.getCell(2).toString()); method
so here is your complete code to do that -
try {
// Open the Excel file
FileInputStream fis = new FileInputStream("D:\\Workspace\\test\\src\\test\\testdata.xls");
// Access the required test data sheet
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheet("testdata");
int rowNumber=0;
Iterator<Row> rowIterator = sheet.iterator();
// Traversing over each row of XLSX file
while (rowIterator.hasNext())
{
System.out.println("Running test case "+sheet.getRow(rowNumber).getCell(0).getStringCellValue());
// Run the test for the current test data row
runTest(sheet.getRow(rowNumber).getCell(0).toString(),sheet.getRow(rowNumber).getCell(1).toString());
rowNumber++;
// To check row cell is not empty
if(sheet.getRow(rowNumber)==null)
{
break;
}
}
wb.close();
fis.close();
}
catch (IOException e)
{
System.out.println("Test data file not found");
}
You for should start from 0 and not 1 but you could try using iterator
Adjust following code to your needs
try {
// Open the Excel file
FileInputStream fis = new FileInputStream("D:\\Workspace\\test\\src\\test\\testdata.xls");
// Access the required test data sheet
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheet("testdata");
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) { // cycle throuh all rows
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
if (cellIterator.hasNext()) { //change to while if you need all columns, otherwise if you need the first column leave as it is...
Cell cell = cellIterator.next();
System.out.println("Running test case " + cell.getStringCellValue());
}
}
}
} catch (IOException e) {
System.out.println("Test data file not found");
}
finally
{
if (fis != null)
fis.close();
}
You can also check the type of a column using:
String tmp = "";
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
tmp = cell.getNumericCellValue() + "";
break;
case Cell.CELL_TYPE_STRING:
tmp = cell.getStringCellValue();
break;
// case Cell.<other types>: ... ; break;
}