Mockito 不断返回空列表

Abu*_*han 2 java spring unit-testing mockito

我正在对 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");
    }
Run Code Online (Sandbox Code Playgroud)

这是不断返回我在 mockito 中模拟的列表并向其中添加一个项目的语句,在这里它返回一个空列表。

debtAccountTransactionList = debtAccountTransactionDao
                .getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null);
Run Code Online (Sandbox Code Playgroud)

然后当然会被这条线抓住

if (debtAccountTransactionList.isEmpty()) {
        throw new SfcException("DISPLAY.PAYMENT_PLAN_WITH_NO_BALANCE_SERVICE_FILE_CLOSED");
    }
Run Code Online (Sandbox Code Playgroud)

因此,为了避免这条执行路径,我在 Mockito 中做了以下工作:

when(debtAccountTransactionDao.getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null)).thenReturn(
            debtAccountTransactionList);
Run Code Online (Sandbox Code Playgroud)

和debtAccountTransactionList 的声明是:

DebtAccountTransaction debtAccountTransaction = spy(DebtAccountTransaction.class);
    debtAccountTransaction.setId(2L);


    List<DebtAccountTransaction> debtAccountTransactionList = new ArrayList<DebtAccountTransaction>();
    debtAccountTransactionList.add(debtAccountTransaction);
Run Code Online (Sandbox Code Playgroud)

我尝试模拟一个列表,尝试了不同的参数捕获器,但似乎没有任何效果。当我调试它时,Mockito 确实填充了DebtAccountTransactionList但有一个空列表,因此它失败了。

关于如何确保 Mockito 发送非空非零列表以便它可以绕过isEmpty()检查的任何帮助。

Dan*_*den 5

编写测试的一个很好的经验法则,尤其是像 Mockito 这样的模拟库:不要将存根与验证混淆。打桩(when)即将测试(SUT)让你的系统进入期望的状态,没有关于主张如何在SUT的行为什么。

在 Mockito 中,对 SUT 的行为进行断言的方法是SUT 运行之后,使用verify调用。如果您没有任何verify调用,则您实际上并未断言任何内容,并且您的 SUT 可能会在没有您的测试捕捉到它的情况下出现异常行为,这显然是一件坏事。

因此,通常最好使用于 stubbing ( when) 的匹配器尽可能广泛,因为 stubbing 的目标只是为了确保您落入正确的测试用例。例如,您可以并且经常应该any()在您的when()通话中使用匹配器。如果你这样做了,你就会回避你在这里遇到的问题。

如果您想对 SUT 实际用作参数的值进行断言,请使用verify,或者可能通过捕获该值并直接对其进行附加断言来实现。