我正在寻找一种“模拟”自动装配组件内部方法的方法。
例如,my 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()?
感谢您的任何建议和帮助
问题来源:Stack Overflow
您可以@MockBean像这样在测试中使用(如果@RunWith(SpringRunner.class))
@MockBean private MeterManagementService meterManagementService
它将被嘲笑并注入。
如果您不使用或不能使用SpringRunner构造函数/设置器来设置依赖项,那么您将能够提供模拟实例并随意使用它。
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。