使用 Mockito when().thenReturn() 存根时返回 NullPointerException

问题描述 投票:0回答:1

我有这个界面:

public interface BindingStubHelper {

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

这是实现:

@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;
  }
}

我在我的应用程序中将其称为:

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

我有 BDD 测试,我试图模拟响应。其中我有:

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);

我在

NullPointerException
线上得到了
.generatePayments(paymentRequest))
。我做错了什么?

java spring spring-boot mockito stubbing
1个回答
0
投票

因为

bindingStubHelper
是一个模拟,如果您希望调用
.getBindingStub()
返回任何内容,您首先必须定义您希望它返回的内容。

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

现在它返回一个模拟,定义调用

generatePayments
时应该发生什么。

when(mockedBindingStub.generatePayments(paymentRequest)).thenReturn(payments);
© www.soinside.com 2019 - 2024. All rights reserved.