Getting java.lang.NullPointerException when trying to use #FindBy in webDriver - java

I am getting java.lang.NullPointerException when i am trying to find elements on a webpage using #FindBy annotation.
My Code -
public class pageObject{
WebDriver driver;
#FindBy(id = "email")
WebElement searchBox;
#FindBy(id = "u_0_v")
WebElement submit;
void pageObject(String web){
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
this.driver = new FirefoxDriver(profile);
this.driver.get(web);
this.driver.manage().window().maximize();
this.driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
searchBox.click();
searchBox.sendKeys("er");
submit.click();
}
public static void main(String[] args){
new pageObject("https://www.facebook.com/?_rdr=p");
}
}
I got an exception for the above code -
Exception -
Exception in thread "main" java.lang.NullPointerException
at com.Selenium_Practice.pageObject.<init>(pageObject.java:29)
at com.Selenium_Practice.pageObject.main(pageObject.java:35)
I also tried to use
#FindBy(how = HOW.ID , using = "email") and #FindBy(how = HOW.ID , using = "u_0_v")
but again got the same null pointer exception

You first need to init your Elements if you use Selenium's PageFactory and if you want your class to be self-containing*
pageObject(String web){
FirefoxProfile profile = new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
this.driver = new FirefoxDriver(profile);
// You need to put this line in your constructor
PageFactory.initElements(this.driver, this);
// Then follows the rest of your constructor
...
}
* meaning, that you could also init this classes elements outside the class, but I presume you want to do it inside.

Related

while using id and xpath i am getting error but while using name i am not getting error

public class First {
public static String browser = "chrome";
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
if (browser.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
if (browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
driver.get("https://www.salesforce.com/in/");
driver.findElement(
By.xpath("//*[#id=\"main\"]/div[2]/div/div/div/div[2]/div[1]/div[1]/div[3]/div/div[1]/div/a")).click();
Set<String> windowHandles = driver.getWindowHandles();
Iterator<String> windowIterator = windowHandles.iterator();
String parentWindow = windowIterator.next();
String childWindow = windowIterator.next();
System.out.println(driver.getTitle());
driver.switchTo().window(childWindow);
System.out.println(driver.getTitle());
driver.findElement(By.id("UserFirstName-m8NQ")).sendKeys("sam");
driver.findElement(By.xpath("//*[#id='UserFirstName-m8NQ']")).sendKeys("sam");
driver.findElement(By.name("UserFirstName")).sendKeys("sam");`
When I am using
driver.findElement(By.id("UserFirstName-m8NQ")).sendKeys("sam");
Or
driver.findElement(By.xpath("//*[#id='UserFirstName-m8NQ']")).sendKeys("sam");
I get the following error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id='UserFirstName-m8NQ']"}
In case I use By.name I am not getting any error. Here the example:
driver.findElement(By.name("UserFirstName")).sendKeys("sam");
Try the below xpath.
//input[contains(#id, 'UserFirstName')]
When you use dynamic content that appends with id, It changes frequently.
By the way, I could able to find using the xpath,
//input[#id='UserFirstName-Q2n8']

java.lang.NullPointerException when using webdriver manager selenium java

While using selenium with java, WebdriverManager is not running and the below code is giving null pointer exception. I have returned the driver at end of class.
I have one ask whether should I keep the Webdriver driver as static or not.
import io.github.bonigarcia.wdm.WebDriverManager;
public class Browserselector {
public WebDriver driver;
public static Properties prop;
public WebDriver initializeDriver() throws IOException {
{
String browserName = "firefox";
System.out.println(browserName);
if (browserName.contains("Chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.contains("IE")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if (browserName.contains("FireFox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if (browserName.contains("EDGE")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
}
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("google.com");
return driver;
}
}
Thanks for your help in advance.
you are trying to start "firefox" - but the if condition checks for "Firefox", if you want to use it like that change the following condition
browserName.contains("FireFox")
into
browserName.equalsIgnoreCase("FireFox")
I recommend you to change the nested if with a "switch" it's more readable and easy to follow/understand
Also, don't use a URL without specifying the protocol
driver.get("https://www.google.com");

java.lang.NullPointerException while executing second #test annotated method using Selenium TestNG and Java

java.lang.NullPointerException while executing second #test annotated method using Selenium TestNG and Java
Code trial:
public class Dropdown {
WebDriver driver;
#BeforeTest
public void Lanchdriver()
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\admin\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver =new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.suzukimotorcycle.co.in/find-dealer");
WebElement dropdown1= driver.findElement(By.xpath("//*[#id='dealer_touch_points']"));
dropdown1.click();
Select select = new Select (dropdown1);
select .selectByVisibleText("Suzuki Premium Dealers");
}
#Test(priority=1)
public void select_dealer()
{
WebElement State_Dropdown =driver.findElement(By.id("dealer_state"));
Select State_Select =new Select (State_Dropdown);
State_Select.selectByValue("27");
}
}
Error:
FAILED: select_dealer java.lang.NullPointerException at myNewPackage.Dropdown.select_dealer(Dropdown.java:47)
You already have declared a global instance of WebDriver i.e. driver as in:
WebDriver driver;
So you need not create any more method level instances of WebDriver and continue using the same instance of WebDriver with global scope i.e. driver.
Solution
You need to remove the word WebDriver from the line WebDriver driver =new ChromeDriver(); within select_dealer() method. Hence, effectively your line of code will be:
driver = new ChromeDriver();
Update below line from beforeTest method
WebDriver driver =new ChromeDriver();
to
driver =new ChromeDriver();
because in your case scope will be limited to that BeforeMethod only. If you want to use same instance outside then declare at class level.
in your case, after execute beforeMethod your driver value got null. that is why getting nullpointer in Test method.

Selenium PageObject throws Invocation Target Exception

I am trying to create a framework(Selenium+TestNg+java) for a Web app(The environment is MacOs+ChromeDriver and the driver server is in \usr\local\bin) but got stuck in basic structure. I have a class(Driversetup.java) that starts the browser, another one that contains WebElements and methods(ProfileUpdateObjects.java) and the third one containing test methods. Now, when I try to run this TestNG class having just a single method, I get following exception.
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at org.openqa.selenium.support.PageFactory.instantiatePage(PageFactory.java:138).
Below is the code (All the classes are in different packages).
public class ProfileUpdateTest {
#Test(enabled = true, priority = 1)
public void profileUpdate() throws MalformedURLException, InterruptedException, ParseException {
WebDriver driver = DriverSetup.startBrowser("chrome");
ProfileUpdateObjects pu = PageFactory.initElements(driver, ProfileUpdateObjects.class);
pu.navigateProfile();
}
}
The code for ProfileUpdateObject class
public class ProfileUpdateObjects {
WebDriver driver;
public ProfileUpdateObjects(WebDriver cdriver) {
this.driver = cdriver;
}
#FindBy(xpath = " //div[#class='ico-menu']")
private WebElement menu;
#FindBy(xpath = "//a[#title='My Dashboard']")
private WebElement myDashboard;
#FindBy(xpath = " //a[contains(text(),'View Profile')]")
public WebElement profile;
#FindBy(xpath = "//li[contains(text(),'Permanent Address')]")
private WebElement permanentAddress;
#FindBy(xpath = "//li[contains(text(),'Banking Information')]")
private WebElement bankingInformation;
WebDriverWait waitfor = new WebDriverWait(driver, 2000);
public void navigateProfile() throws InterruptedException {
menu.click();
profile.click();
waitfor.until(ExpectedConditions.visibilityOf(permanentAddress));
}
}
DriverSetup.java
public class DriverSetup {
public static WebDriver driver;
public static WebDriver startBrowser(String browserName, String url) {
if (browserName.equalsIgnoreCase("chrome")) {
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
It is failing in pu.navigateProfile() call. Also, is it true that #FindBy takes more memory compared to driver.find() syntax and besides POM are there any other design principles for Automation framework because most of the resources over Web are one or the other implementation of POM.
Simple solution is to move new WebDriverWait. It should not be instantiated as instance variable.
Instead of:
WebDriverWait waitfor = new WebDriverWait(driver, 2000);
public void navigateProfile() throws InterruptedException {
menu.click();
profile.click();
waitfor.until(ExpectedConditions.visibilityOf(permanentAddress));
}
Use:
public void navigateProfile() {
menu.click();
profile.click();
new WebDriverWait(driver, 2000).until(ExpectedConditions.visibilityOf(permanentAddress));
}
This will solve your issue (Already tested it)

NullPointerException when running my test with page factory

I get an exception when I run my test. I am using selenium with page factory. When I run following code ,it will open up the website and fail with exception below. it doesn't perform the HomePage.ClickbtnCookieWarning() in my test case.
Can someone please help me to understand why my code isn't working?
FAILED CONFIGURATION: #BeforeTest SetUp java.lang.NullPointerException
at
org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at
org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.click(Unknown Source) at
pageObjects.HomePage.ClickLoginLink(HomePage.java:57) at
myaccountsuite.TC1DefaultDeliveryAddDisplay.SetUp(TC1DefaultDeliveryAddDisplay.java:29)
Home Page page object
public class HomePage {
WebDriver driver;
public HomePage (WebDriver driver)
{
this.driver=driver;
}
#FindBy(id="ctl00_header_hdrCookieWarning_btnHideCookieWarning")
WebElement btnCookieWarning;
#FindBy(xpath=".//*#id='ctl00_masterContainerTop_Block_637_LoginView1_ulAnonymous']/li[2]/a")
WebElement LoginLink;
public void ClickbtnCookieWarning()
{
btnCookieWarning.click();
}
public void ClickLoginLink()
{
LoginLink.click();
}
}
Login Page Object
public class login {
WebDriver driver;
public login(WebDriver driver)
{
this.driver = driver;
}
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_UserName")
WebElement UserName;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_Password")
WebElement Password;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_LoginButton")
WebElement btn_LogIn;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_txtAccount")
WebElement Account;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_btnHomeBranch_3")
WebElement btn_Continue;
public void userLogin(String uname, String pass, String acc)
{
UserName.sendKeys(uname);
Password.sendKeys(pass);
btn_LogIn.click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Account.sendKeys(acc);
btn_LogIn.click();
btn_Continue.click();
}
}
My Test
public class TC1DefaultDeliveryAddDisplay {
public WebDriver driver;
#BeforeTest(alwaysRun = true)
public void SetUp() {
HomePage HomePage = PageFactory.initElements(driver, HomePage.class);
login loginpage = PageFactory.initElements(driver, login.class);
driver = new FirefoxDriver();
driver.get("http://URL/");
HomePage.ClickbtnCookieWarning();
HomePage.ClickLoginLink();
loginpage.userLogin("aa#yahoo.com", "125", "Test");
}
You're getting NullPointerException because you're using WebDriver instance before initialising.
You need to Initialize WebDriver before using this instance as :-
driver = new FirefoxDriver();
HomePage HomePage = PageFactory.initElements(driver, HomePage.class);
Login loginpage =PageFactory.initElements(driver, login.class);
If you want to use WebDriver as singleton which returns single instance for all your test methods you can follow this answer which is exactly you want.
The problem is in each class you are creating new instance of driver. You just need to create one driver instance in you base class where you do your browser setup. Please refer Page Object Model. Once the Driver instance is created you need to use the same in all your classes. Or else it will throw NullPointerException because driver will not have any reference.

Categories

Resources