在Mockito中存根方法时,我是否应该使用原始实例或存根实例进行测试?

时间:2016-11-03 11:03:04

标签: java unit-testing mockito

我有一个我想测试的服务方法:

public ScheduleView createSchedule(ScheduleView scheduleView) throws ValidationException {
    scheduleView = (ScheduleView) createObject(scheduleView, ScheduleBean.class);
    sendNotificationScheduleDataChangedToSchedulerDaemon();
    return scheduleView;        
}

sendNotificationScheduleDataChangedToSchedulerDaemon()方法连接到名为ServerService的远程服务,这在单元测试期间不是您想要的。单元测试期间远程服务未运行,因此连接失败。我最好想使用Mockito来保存这个方法,因此它不会被调用:

public void testCRUOperations() {
    // Create the service 
    ScheduleService scheduleService = (ScheduleService) ServiceFactory.getInstance().createService(ScheduleService.class);
    ScheduleService scheduleServiceSpy = spy(ScheduleService.class);
    doNothing().when(scheduleServiceSpy).sendNotificationScheduleDataChangedToSchedulerDaemon();

现在,我的问题是,如何调用createSchedule()方法,以便存根方法不被执行?

scheduleView = scheduleService.createSchedule(newscheduleView);

scheduleView = scheduleServiceSpy.createSchedule(newscheduleView);

我已经尝试了这两种方法,但仍然会执行存根方法,但我的日志中仍然会显示ConnectException

我已经在这里检查了其他问题以及Mockito框架网站,但我无法弄明白。什么是存根方法的正确方法?

1 个答案:

答案 0 :(得分:2)

这对于评论来说太长了,所以把它放在这里。

我不确定存根,但其他一切似乎表明应该完成重构。这个问题清楚地表明,所讨论的方法或与之交互的方法是紧密耦合的,应该被抽象为可注入的依赖

public interface NotificationService {
    void sendNotificationScheduleDataChangedToSchedulerDaemon();
}

public class ScheduleService {
    private NotificationService notificationService;

    public ScheduleService(NotificationService notificationService) {
        this.notificationService = notificationService;
    }

    public ScheduleView createSchedule(ScheduleView scheduleView) throws ValidationException {
        scheduleView = (ScheduleView) createObject(scheduleView, ScheduleBean.class);
        notificationService.sendNotificationScheduleDataChangedToSchedulerDaemon();
        return scheduleView;        
    }
}

现在可以在单元测试期间模拟依赖项,以便它不会触及实际服务,并且将在生产代码中使用具体实现。