Skip to content

NullPointerException using methods in page objects

AutomatorGuy123 edited this page Aug 17, 2019 · 1 revision

Lets examine the following which causes a NullPointerException. There are many problems with the code but we will only focus on the NullPointerException.

Bad Code

@Step("Enter VIN")
private void enterVIN() {
    setElementValueV2(vin);
    VehicleDetails vehicleDetails = new VehicleDetails();
    assertThat("mileage",vehicleDetails.mileage.getText(),equalTo("Insufficient VIN for Verification"));
}

Line 3 (the assertion) is causing the NullPointerException. However, it is not obvious why this occurs. All the getter methods ensure non-null page objects. The first place that could generate a **NullPointerException **is mileage.getText(). The question is why does this cause the NullPointerException? This line of code is being using in the class without a NullPointerException. So, what is the difference here?

Root Cause

The framework is using Selenium's PageFactory class to initialize all components. This is what makes all the components non-null. So, why was this initialization not performed? In the framework, all page objects expose initPage methods which triggers this initialization by Selenium. In addition, many page objects expose a constructor that takes a context. This constructor will call the initPage method.

Solutions

  1. Use the constructor that takes a context
@Step("Enter VIN")
private void enterVIN() {
    setElementValueV2(vin);
    VehicleDetails vehicleDetails = new VehicleDetails(getContext());
    assertThat("mileage",vehicleDetails.mileage.getText(),equalTo("Insufficient VIN for Verification"));
}
  1. Use the initPage method
@Step("Enter VIN")
private void enterVIN() {
    setElementValueV2(vin);
    VehicleDetails vehicleDetails = new VehicleDetails();
    vehicleDetails.initPage(getContext());
    assertThat("mileage",vehicleDetails.mileage.getText(),equalTo("Insufficient VIN for Verification"));
}
Clone this wiki locally