Getting Null value for the Page Object Element in Selenium

page object model with pagefactory in selenium
null pointer exception in page object model
page object model selenium-java example github
page object model best practices
page object model in selenium python
page object model in selenium c#
page object model framework architecture
page object model without page factory

I am working in a cucumber , TestNG, Selenium based project and I have my PageObject page as below

package com.testing.pageobject;

import java.util.List;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import com.testing.components.SearchResultComponent;
import com.testing.stepdefinitions.BaseClass;

public class ShoppingPage extends BaseClass {



    public ShoppingPage(RemoteWebDriver driver) {
        super();
        this.driver=driver;
        PageFactory.initElements(driver, this);

    }

    @FindBy(xpath="//div[@class='sh-dlr__list-result']")
    private List<SearchResultComponent> SearchResult;

    @FindBy(xpath="//span[@class='qa708e IYWnmd']")
    private List<WebElement> ResultListView;

    @FindBy(xpath="//span[@class='Ytbez']")
    private List<WebElement> ResultGridView;

    public List<SearchResultComponent> getSearchResult() {
        return SearchResult;
    }

    public List<WebElement> getResultListView() {
        return ResultListView;
    }

    public List<WebElement> getResultGridView() {
        return ResultGridView;
    }   

}

And my component page as below

package com.testing.components;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

import com.testing.stepdefinitions.BaseClass;

public class SearchResultComponent extends BaseClass {



    public SearchResultComponent(RemoteWebDriver driver) {
         super();
         this.driver=driver;
         PageFactory.initElements(driver, this);
    }

    @FindBy(xpath="//a[@class='AGVhpb']")
    private WebElement productName;

    @FindBy(xpath="//span[@class='O8U6h']")
    private WebElement productPrice;

    @FindBy(xpath="//div[@class='vq3ore']")
    private WebElement productStars;

    @FindBy(xpath="//img[@class='TL92Hc']")
    private WebElement productImage;

    @FindBy(xpath="//div[@class='hBUZL CPJBKe']")
    private WebElement productDescription;

    public WebElement getProductName() {
        return productName;
    }

    public WebElement getProductPrice() {
        return productPrice;
    }

    public WebElement getProductStars() {
        return productStars;
    }

    public WebElement getProductImage() {
        return productImage;
    }

    public WebElement getProductDescription() {
        return productDescription;
    }




}

My cucumber step definition is

@When("search for product less than {int}")
public void search_for_product_less_than(Integer int1) {
    ShoppingPage myshopping = new ShoppingPage(driver);
    List<SearchResultComponent> SearchResults = myshopping.getSearchResult();
    for(SearchResultComponent myResult:SearchResults) {
        System.out.println(myResult.getProductName());
    }
}

Problem Statement :

I am getting null point error when I tried to get the getSearchResult() in the step definition. Not sure why any thoughts how to fix this ?

In Shoppingpage class use WebElement as type instead of class name SearchResultComponent as mentioned below.

@FindBy(xpath="//div[@class='sh-dlr__list-result']")
private List<WebElement> SearchResult;

public List<WebElement> getSearchResult() {
    return SearchResult;
}

Also use webelement in cucumber step definition as well

   @When("search for product less than {int}")
   public static void search_for_product_less_than(Integer int1) {
        ShoppingPage myshopping = new ShoppingPage(driver);
        List<WebElement> SearchResults = myshopping.getSearchResult();
        for(WebElement myResult:SearchResults) {
            System.out.println(myResult.getText());
        }
    }

POM @FindBy List elements throws Null Pointer Exception · Issue , I made ehancements to Selenium itself to facilitate these new FindyBys With any singular Angular element with Page Object your FindBy's are Getting Null pointer error when defining List WebElement using POM for any  sub-actions that provide information about page elements 3.1 get page title. 3.3 get page url. 4.1 get results count value. actions that assert (verify) that information is correct 3.2 verify that page title is correct. 3.4 verify that page url is correct. 4.2 verify that results count value is > 0. 1.3 CONVERT ACTIONS AND SUB-ACTIONS INTO METHODS

The reason is that the needed element is not found in the page. This can have different reasons.

1) You call new ShoppingPage(driver) too early, when page fragment with "//span[@class='qa708e IYWnmd']" is not yet loaded.

2) It can be that the XPath is defined incorrectly and there is no such element on the page. Check your XPath.

Page Object Model in Selenium: Test Automation Made Easy, Page Factory in Selenium is an extension to Page Object and can be used in various ways. In this case we will use Page Factory to initialize web elements that are  When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects. To check if any reference variable is null or not, we can use isNull () method of Objects class. This method returns true if the provided reference is null otherwise returns false. Objects.isNull (np2);

Thanks @Yosuva A . I updated it to WebElement and its working now as below

public void search_for_product_less_than(Integer int1) {
    ShoppingPage myshopping = new ShoppingPage(driver);
    SearchResultComponent resultcomp = new SearchResultComponent(driver);

    List<WebElement> PriceResult = resultcomp.getProductPrice();
    List<WebElement> ProductName = resultcomp.getProductName();
    for(int i=0;i<PriceResult.size();i++) {
        String price = PriceResult.get(i).getText().replace("$", "");
        System.out.println("Price" + Double.valueOf(price));
        if(Double.valueOf(price)<13) {
            System.out.println(price);
            System.out.println(ProductName.get(i).getText());

        }
    }
}  

How to resolve NullPointerException error in my below POM code , Java instead of creating a separate WebDriver object, you can use the WebDriver object of BasePage class directly by using (BasePage.driver)  How can I get the attribute value of a web element in Selenium (either by Python or Java)? 46573/how-attribute-value-web-element-selenium-using-java-python Toggle navigation

How to Implement Page Object and Page Factory Pattern in , class HomePage { WebDriver driver; public HomePage(WebDriver driver) Important: If you call initElements() all elements will be initialized, not later if you use Page Factory Pattern is like an extension to Page Object Model , but Page​  To get the attribute value using selenium webdriver, we can use 'element.getAttribute (attributeName)'. If we try to get the attribute value that doesn't exists for the tag, it will return null value. <button name="btnK" id="gbqfba" aria-label="Google Search" class="gbqfba"><span id="gbqfsa"> Google Search </span></button>

Page Object Model In Selenium With Page Factory, Page Object Model is a design pattern in test automation to create an Object Repository According to the Page Object Model, you should keep the tests and element locators separately. public static WebDriver driver = null ; I hope you understood the concepts and it added value to your knowledge. Meta - OS: OSX Selenium Version: 3.3.1, IntelliJ Browser: Chrome 60 Browser Version: Version 60.0.3112.90 (Official Build) (64-bit) Expected Behavior - No null pointer exception when calling webDriver.findElements Actual Behavior - Occas

Page Object Model using Selenium Webdriver for Automation , I get so many questions regarding Page Object Model framework but let The benefit from this will be, if any changes in web element locators  Documentation for Selenium. Web element WebElement represents a DOM element. WebElements can be found by searching from the document root using a WebDriver instance, or by searching under another WebElement.

Comments
  • Are you sure that exception occurres in myshopping.getSearchResult()? Not in the for loop?
  • List<SearchResultComponent> SearchResults = myshopping.getSearchResult(); For SearchResults itself i am geting null value , on passing in to for loop is the reason for this Null point error
  • I'd step through your code on PageFactory.initElements(driver, this);. It's possible that it's not being initialized because it can't find them?
  • Hi thanks for the update . I understood the reason but not sure how to get the Product Name alone just by passing the SearchResult as a component to be iterated . I have crosschecked the xpath and its referring to the correct elements only. So it should not be an issue i Guess
  • There is no magic. If the attribute is null, it means that there is no such element on the page. You can check it by driver.findElements(By.xpath("...")). Add such check temporarily before you call new ShoppingPage(driver). If this direct search also returns null, it will confirm that either XPath is wrong or that the element really does not exist.