java - 使用 Spring、JUnit 和 Mockito 在自动装配组件中模拟一个方法
问题描述
我正在寻找一种在 Autowired 组件中“模拟”方法的方法。
例如,我PersistService
包含一个方法,如:
@Autowired
MeterManagementService meterManagementService;
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Override
public void doPersist(HouseholdUpdateServiceCall householdUpdateServiceCall) throws Exception {
LOG.info("doPersist start()");
if (householdUpdateServiceCall.getHhId() > -1) {
saveUboPanelInfo(householdUpdateServiceCall);
saveUboSites(householdUpdateServiceCall);
if (householdUpdateServiceCall.getHouseholdUpdateRequest() != null
&& householdUpdateServiceCall.getHouseholdUpdateRequest().getPeopleMeter() != null
&& householdUpdateServiceCall.getHouseholdUpdateRequest().getPeopleMeter().getPeople() != null
&& householdUpdateServiceCall.getHouseholdUpdateRequest().getPeopleMeter().getPeople().getPerson() != null) {
Integer panelId = new Long(householdUpdateServiceCall.getPanelId()).intValue();
Integer hhId = new Long(householdUpdateServiceCall.getHhId()).intValue();
Integer personCount = householdUpdateServiceCall.getHouseholdUpdateRequest().getPeopleMeter().getPeople().getPerson().size();
LOG.info("storePersonCount for panelId: " + panelId + ", hhId: " + hhId + ", personCount: " + personCount);
uboPanelDao.storePersonCount(hhId, personCount, panelId);
}
String result = meterManagementService.getResult();
LOG.info("The result is: " + result);
LOG.info("doPersist end()");
}
}
Junit 测试包含:
@Autowired
PersistService persistService;
//normal success scenario
@Test
public void test03() {
try {
HouseholdUpdateServiceCall householdUpdateServiceCall = new HouseholdUpdateServiceCall();
householdUpdateServiceCall.setCPCount(0);
householdUpdateServiceCall.setHhId(1L);
householdUpdateServiceCall.setPanelId(1L);
//how to mock the method which is used inside doPersist and it is autowired in persistService?
persistService.doPersist(householdUpdateServiceCall);
...
我正在寻找的是如何String result = meterManagementService.getResult()
在persistService
? 例如,如何为 设置一个值“OK” meterManagementService.getResult()
?
感谢您的任何建议和帮助
解决方案
你可以@MockBean
像这样在你的测试中使用(如果@RunWith(SpringRunner.class)
)
@MockBean private MeterManagementService meterManagementService
它将被模拟和注入。
如果您不使用或无法SpringRunner
使用构造函数/设置器来设置依赖项 - 您将能够提供模拟实例并随意使用它。
推荐阅读
- c++ - C++不能使用从基类继承的getter函数
- mysql - 如何在带有 node.js 的 typescript-sequelize 中使用“或”选项?
- angular - 模态关闭和表单值重置在 Angular 中不起作用
- mariadb - 如何在 RHEL 7 服务器上安装 MariaDB?
- angular - 单击眼睛图标时,Angular Ionic 3 输入将注意力集中在密码字段上
- spring-boot - 正在创建的未知线程池
- c# - 使用 C# 使用调酒师动态更改数据源
- python - 将字典添加到字典或列表中会显示重复项
- json - 使用条件语句的 json 模式定义
- r - kable/kableExtra 为 group_rows 中的组标签添加上标