gpt4 book ai didi

Java Mockito 模拟方法时出现 InvalidUseOfMatchersException

转载 作者:行者123 更新时间:2023-12-02 09:19:43 26 4
gpt4 key购买 nike

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

    @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。

关于Java Mockito 模拟方法时出现 InvalidUseOfMatchersException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58769714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com