繁体   English   中英

使用Mockito模拟帮助类

[英]Mocking helper class with Mockito

我有一个简单的帮助程序类,其中包含在服务级别类中使用的公共方法。 当我为服务类编写测试并尝试为一种方法模拟该帮助程序类时,它进入方法内部并运行每一行。 由于此方法中的代码更复杂,因此我想用方法模拟助手类,这样我就不必照顾助手类方法中的每个细节。

服务等级

class HistoryServiceImpl implements CaseHistory {
  @Override
  public List<CaseHistoryDto> getCaseHistory(Individual member, Individual provider) {
    MemberUtil memberUtil = new MemberUtil();
    List<CaseHistoryDto> caseHistoryDtoList = new ArrayList<CaseHistoryDto>();
    List<CaseHistory> caseHistoryList = caseDetailDao.fetchCaseHistory(member.getId(), provider.getId());
    for(CaseHistory caseHistory : caseHistoryList) {
        CaseHistoryDto caseHistoryDto = new CaseHistoryDto();
        caseHistoryDto.setMemberInfo(memberUtil.getMemberInfo(member, caseHistory.getCreateDate()));
        caseHistoryDtoList.add(caseHistoryDto);
    }
    return caseHistoryDtoList;
  }
}

测试班

Class HistoryServiceTest {
  @Mock MemberUtil memberUtil;
  @InjectMocks private HistoryServiceImpl historyServiceImpl = new HistoryServiceImpl();

  @Test
  public void testGetCaseHistory() {
    //why this line going inside real method and executing all lines?
    when(memberUtil.getMemberInfo(any(Individual.class), any(Date.class))).thenReturn(member);
  }
}

您的测试用例正在“真实”方法中运行所有行的原因是,您的模拟对象从未在任何地方使用。

如所写,您不能在HistoryServiceImpl模拟MemberUtil ,因为您正在getCaseHistory()方法中手动实例化它。 您需要使getCaseHistory()从其他位置获取其MemberUtil ,以便可以将模拟版本注入测试类中。

最简单的解决方案是将MemberUtil定义为成员变量,以便@InjectMocks批注可以覆盖默认值:

class HistoryServiceImpl implements CaseHistory {
    MemberUtil memberUtil = new MemberUtil();

    @Override
    public List<CaseHistoryDto> getCaseHistory(Individual member, Individual provider) {
        ...
    }
}

或者,您可以让HistoryServiceImpl在其构造函数中或通过setter方法接受外部提供的MemberUtil 然后,您可以轻松地在测试类中传递模拟版本。

通常,实用程序类是无状态的,因此另一种可能的解决方案是将MemberUtil转换为使其所有方法静态化。 然后,您可以使用PowerMock之类的东西来模拟您的静态方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM