我正在对 Mockito 中的方法进行单元测试,即使我已经初始化了要返回的列表,mockito 仍会发送一个空的零大小列表。
这是要测试的代码。请注意,nonCashIncludedPaymentPlanActive 始终为真(模拟)。
List<DebtAccountTransaction> debtAccountTransactionList = null;
boolean nonCashIncludedPaymentPlanActive = balancingPlanService.checkNonCashIncludedPaymentPlanParameter(debtAccountId);
if (nonCashIncludedPaymentPlanActive) {
debtAccountTransactionList = debtAccountTransactionDao
.getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null);
}
if (debtAccountTransactionList.isEmpty()) {
throw new SfcException("DISPLAY.PAYMENT_PLAN_WITH_NO_BALANCE_SERVICE_FILE_CLOSED");
}
这个语句不断返回我在 mockito 中模拟的列表并向其中添加了一个项目,在这里它返回一个空列表。
debtAccountTransactionList = debtAccountTransactionDao
.getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null);
当然会被这条线捕获
if (debtAccountTransactionList.isEmpty()) {
throw new SfcException("DISPLAY.PAYMENT_PLAN_WITH_NO_BALANCE_SERVICE_FILE_CLOSED");
}
因此,为了避免这种执行路径,我在 Mockito 中做了以下操作:
when(debtAccountTransactionDao.getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null)).thenReturn(
debtAccountTransactionList);
debtAccountTransactionList 的声明是:
DebtAccountTransaction debtAccountTransaction = spy(DebtAccountTransaction.class);
debtAccountTransaction.setId(2L);
List<DebtAccountTransaction> debtAccountTransactionList = new ArrayList<DebtAccountTransaction>();
debtAccountTransactionList.add(debtAccountTransaction);
我尝试模拟一个列表,尝试不同的参数捕获器,但似乎没有任何效果。当我调试它时,Mockito 确实填充了 debtAccountTransactionList 但列表为空,因此它失败了。
关于如何确保 Mockito 发送非空非零列表以便它可以绕过 isEmpty() 检查的任何帮助。
最佳答案
编写测试的一个很好的经验法则,尤其是对于像 Mockito 这样的模拟库:不要混淆 stub 和验证。 stub (when
)是关于让您的被测系统 (SUT) 进入所需状态,不是断言关于 SUT 行为的任何事情。
在 Mockito 中,断言 SUT 行为方式的方法是 在 SUT 运行之后,使用 verify
调用。如果您没有任何 verify
调用,那么您实际上并没有断言任何东西,并且您的 SUT 可能会在您的测试未捕获到它的情况下出现异常行为,这显然是一件坏事。
因此,通常最好使用于 stub (when
) 的匹配器尽可能广泛,因为 stub 的目的只是确保您进入正确的测试用例。例如,您可以并且经常应该在 when()
调用中使用像 any()
这样的匹配器。如果你这样做,你就会回避你在这里遇到的问题。
如果您想对 SUT 实际用作参数的值进行断言,请使用 verify
进行,或者可能通过捕获该值并直接对其进行其他断言。
关于java - Mockito 不断返回空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52497746/