【发布时间】:2020-02-27 19:42:46
【问题描述】:
我想在我的 Invoice 类中存根方法 generateReferenceNumber():
public class Invoice {
private String id;
private String referenceNumber;
private Date issueDate;
private PaymentMethod paymentMethod;
private Date paymentDate;
private String shopId;
private List<InvoiceGroupItem> groupItems;
private InvoiceStatus status;
public void moveToNextState() {
status = status.nextState();
}
public void generateReferenceNumber() {
if (referenceNumber != null) {
return;
}
referenceNumber = new InvoiceReference().createNew(issueDate).toString();
}
}
此对象用于我要测试的服务。为此,我需要多张发票。所以我写了以下代码:
private Stream<Invoice> buildApprovedInvoice() {
val approvedInvoices = new ArrayList<Invoice>();
for (int i = 0; i < 10; i++) {
val invoice = Invoice.builder().build();
val spy = spy(invoice);
doAnswer(invocation -> {
final Invoice mock = (Invoice) invocation.getMock();
mock.setReferenceNumber("Invoice reference number");
return null;
}).when(spy).generateReferenceNumber();
approvedInvoices.add(spy);
}
return approvedInvoices.stream();
}
当我执行测试时,出现以下错误:
org.mockito.exceptions.misusing.UnfinishedStubbingException: 此处检测到未完成的存根: -> 在 com.coruscant.core.services.invoice.InvoiceSendingServiceTest.sendInvoices(InvoiceSendingServiceTest.java:54)
例如thenReturn() 可能会丢失。正确的存根示例: 当(模拟。isOk())。然后返回(真); when(mock.isOk()).thenThrow(异常); doThrow(exception).when(mock).someVoidMethod();
有人知道为什么吗?
谢谢。
【问题讨论】:
-
我很确定异常不是来自您问题中显示的代码。你能提供一个产生异常的minimal reproducible example 吗?