为什么我的方法在我验证它在 junit 中被调用后继续工作?

Why does my method keep on working after I verify it was called in junit?

我正在尝试测试以下方法:

public void transactionToBN() {

        List<CustomerDelivery> list = getListOfArticleByStatusA();
        ...
        ...
        if (!list.isEmpty() || list != null) {

            Hashtable<String, Order> docIds = new Hashtable<>();

            for (int i = 0; i < list.size(); i++) {
                try{
                    ...Some functionalities..

                }catch(Throwable t){
                    countNumId++;
                }
            }
            if (!docIds.isEmpty())
                orderTransfer(docIds);
        }
        
    }

我的测试:

@Test
    public void canDoTransactionToBN() {
        customerDelivery = new CustomerDelivery();
        customerDelivery.setCD_COM1("1");
        List<CustomerDelivery> customerDeliveries = new ArrayList<>();
        customerDeliveries.add(customerDelivery);
        Hashtable<String, Order> docIds = new Hashtable<>();
        CustomerDeliveryService spy = Mockito.spy(CustomerDeliveryService.class);

        //when
        Mockito.doReturn(customerDeliveries).when(spy).getListOfArticleByStatusA();
        Mockito.doNothing().when(spy).orderTransfer(docIds);
        spy.transactionToBN();

        Mockito.verify(spy).orderTransfer(docIds);
    }

所以我基本上只是想测试是否调用了 orderTransfer()。我 运行 遇到的问题是我得到一个在 orderTransfer() 内部调用的方法的空指针,这是我不想用这个单元测试的东西。我试过 .doNothing() 这样代码就不会继续运行,但由于某种原因它会继续运行。我尝试验证方法调用的方式是否有问题,或者是否调用了整个页面的代码,而不仅仅是 transactionToBN()?

看起来您只是在使用 docIds 调用 orderTransfer 时存根。我假设它是用 docIds 之外的东西调用的,所以它仍在使用 un stubbed 方法。

尝试用 Mockito.doNothing().when(spy).orderTransfer(any());

替换存根

这里有关于参数匹配器 (any()) 的更多详细信息 https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html