javaspringspring-bootmockitostubbing

NullPointerException returned when using Mockito when().thenReturn() stubbing


I have this interface:

public interface BindingStubHelper {

  public BindingStub getBindingStub()
      throws java.rmi.RemoteException;
}

This is the implementation:

@Configuration
public class BindingStubImpl implements BindingStubHelper {

  @Value("${my.url}")
  private URL url;

  @Override
  public BindingStub getBindingStub()
      throws java.rmi.RemoteException {
    BindingStub BindingStub = new BindingStub(url, null);
    return BindingStub;
  }
}

I call it in my applicaiton with:

@Autowired private BindingStubHelper bindingStub;
...
payments = bindingStub.getBindingStub().generateSchedule(paymentRequest);

I have BDD tests where I'm trying to mock the response. In it I have:

Payment payments =
        new Payment(
            34.97,
            22.58304,
            0.0,
            0.0,
            534.97,
            0,
            0,
            7.0,
            installmentList,
            500,
            500,
            500,
            500,
            10,
            500,
            0.0,
            20.00);
    PaymentRequest paymentRequest =
        new PaymentRequest(
            500.0,
            startDate,
            renewalDate,
            Source.Annex,
            "838",
            "065714",
            "MQ",
            Type.New);
    when(bindingStubHelper
            .getBindingStub()
            .generatePayments(paymentRequest))
        .thenReturn(payments);

I get a NullPointerException on the line .generatePayments(paymentRequest)). What am I doing wrong?


Solution

  • Because bindingStubHelper is a mock, if you expect the call to .getBindingStub() to return anything, you'll first have to define what you want it to return.

    when(bindingStubHelper.getBindingStub()).thenReturn(mockedBindingStub);
    

    Now that it's returning a mock, define what should happen when the call to generatePayments is made.

    when(mockedBindingStub.generatePayments(paymentRequest)).thenReturn(payments);