-
Notifications
You must be signed in to change notification settings - Fork 2
NullPointerException using methods in page objects
Lets examine the following which causes a NullPointerException. There are many problems with the code but we will only focus on the NullPointerException.
@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?
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.
- 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")); }
- 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")); }