首页 > 解决方案 > 使用 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()

感谢您的任何建议和帮助

标签: javaspringjunitmockito

解决方案


你可以@MockBean像这样在你的测试中使用(如果@RunWith(SpringRunner.class)

@MockBean private MeterManagementService meterManagementService

它将被模拟和注入。

如果您不使用或无法SpringRunner使用构造函数/设置器来设置依赖项 - 您将能够提供模拟实例并随意使用它。


推荐阅读