【发布时间】:2018-09-25 12:00:25
【问题描述】:
我正在对 Mockito 中的一个方法进行单元测试,即使我已经初始化了要返回的列表,mockito 也会继续发送一个空的零大小列表。
这是要测试的代码。请注意,nonCashIncludedPaymentPlanActive 始终为 true ( Mocked )。
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 中模拟的 List 并向其中添加了一个项目,在这里它返回一个空列表。
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() 检查的帮助。
【问题讨论】:
-
问题不在于创建 Mocks,问题在于 debcountTransactionList 被返回为 Null 或零大小。
-
当使用一个集合(看起来是这样)时,请确保该集合的类型相同,并且其中的元素具有正确的 equals/hashcode 实现。否则 Mockito 不会将其视为匹配项并返回一个空列表(默认行为)。
-
问题是模拟创建/行为注册。这与您放入方法中的内容不匹配,因此返回到返回空列表的默认行为。
-
能否请您发布整个测试类以及依赖项、注释?
-
我明白了,我可以将它与传递给 debtAccountTransactionDao.getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null) 的任何 List
参数相匹配 我的意思是而不是 baseDebtIdAccountList,我想要它接受任何长列表。我尝试使用参数匹配器,但它们似乎不起作用并导致错误。我在代码中还有一份 baseDebtIdAccountList 的副本,所以有什么方法可以检查以确保 baseDebtIdAccountList 等于我传入的 baseDebtIdAccountList。
标签: java spring unit-testing mockito