Java 模拟方法时 Mockito InvalidUseOfMatchersException

Java Mockito InvalidUseOfMatchersException when mocking method

我在使用 mockito 2.23.4、junit4 和 springrunner 测试方法时遇到困难。我不断收到 InvalidUseOfMatchersException,即使代码对我来说看起来非常好。我不确定我到底错过了什么。任何提示都会对我很有帮助。我将 post 下面的代码。

    @RunWith(SpringRunner.class)
    public class FiscalClosingServiceImplTest {
        @InjectMocks
        private FiscalClosingServiceImpl fiscalClosingServiceImpl;
        @Mock
        private IDataBeanManager dataBeanManager;
        @Mock
        private IFiscalClosingPopulator fiscalClosingPopulator;
        @Mock
        private DataBean dataBean;
        @Test
        public void test_getFiscalClosingListByNodeIdAndSiteId_WhenListNotEmpty() throws ServiceException {
            //Arrange
            List<DataBean> dataBeansResult = new ArrayList<DataBean>();
            dataBeansResult.add(dataBean);
            when(dataBeanManager.listBeansByAttributeValue(anyString(), anyString(), anyString(), anyString())).thenReturn(dataBeansResult);
            String siteId = "siteId";
            FiscalClosing fiscalClosingTest = new FiscalClosing();
            fiscalClosingTest.setSiteId(siteId); 
 when(fiscalClosingPopulator.convertBeanToFiscalClosing(any(DataBean.class))).thenReturn(fiscalClosingTest);

        //Act
        List<FiscalClosing> result = fiscalClosingServiceImpl.getFiscalClosingListByNodeIdAndSiteId(anyString(), eq(siteId));

        //Assert
        assertEquals(result.get(0).getSiteId(), fiscalClosingTest.getSiteId());
    }
}

下面要测试的方法:

@Override
    public List<FiscalClosing> getFiscalClosingListByNodeIdAndSiteId(final String nodeId, final String siteId)
            throws ServiceException {
        log.debug("Retrieving FiscalClosing by transactionLastUpdatedDateTime");
        List<FiscalClosing> fiscalClosingList = new ArrayList<FiscalClosing>();

        List<DataBean> dataBeans = dataBeanManager.listBeansByAttributeValue(
                EntityConstant.getConstant(CONSTANTS.FISCAL_CLOSING_ID),
                EntityConstant.getConstant(CONSTANTS.FISCAL_CLOSING_NODE_ID_ID), nodeId, "");

        if(dataBeans.isEmpty()) {
            return fiscalClosingList; 
        }

        for(DataBean dataBean : dataBeans) {
            FiscalClosing fiscalClosing = fiscalClosingPopulator.convertBeanToFiscalClosing(dataBean);
            fiscalClosingList.add(fiscalClosing);
        }

        return fiscalClosingList.stream().filter(item -> item.getSiteId().equals(siteId)).collect(Collectors.toList());
    }

在测试的 "Act" 部分,您使用参数匹配器作为被测方法的参数:

List<FiscalClosing> result = fiscalClosingServiceImpl.getFiscalClosingListByNodeIdAndSiteId(anyString(), eq(siteId));

你不能像这样使用匹配器,它们应该用于以更通用的方式定义模拟的行为。调用该方法时,您应该传递实际值,尽管它们不一定有效,具体取决于您如何模拟该方法的其余部分。

在你的情况下,它可以像这样简单:

List<FiscalClosing> result = fiscalClosingServiceImpl.getFiscalClosingListByNodeIdAndSiteId("nodeId", "siteId");

然后您可能必须更新测试以确保返回正确的站点 ID。