希望但不调用JPA单元测试用例删除操作

时间:2019-04-09 08:47:45

标签: java unit-testing jpa mockito

在尝试创建要用JPA删除的junit测试用例时遇到了一些问题。在服务类中,我使用的是JPA提供的默认功能:

public void delete(Long id) {
        log.debug("Request to delete Enroll : {}", id);
        enrollRepository.deleteById(id);
}

然后进行单元测试,我试图模拟一个对象,然后执行删除操作:

@Test
public void testDeleteEnrollExpectSuccess() {
    Enroll enroll = prepareEnrollWithBedAllocation();
    enrollService.delete(enroll.getId());
    verify(enrollRepository, times(1)).delete(enroll);
}

我想像这样模拟注册对象:

private Enroll prepareEnrollWithBedAllocation() {
    LocalDateTime localDateTime = LocalDateTime.now();
    ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("UTC"));

    Enroll enroll = new Enroll();
    enroll.setId(new Long(1));
    enroll.seteDate(zonedDateTime);
    enroll.setEbStartdt(zonedDateTime);
    enroll.setEbEnddt(zonedDateTime);
    enroll.setBed(prepareBed());
    enroll.setPatient(preparePatient());
    enroll.setDoc(prepareDoc());
    enroll.seteCondition("Normal");
    return enroll;
}

但是,我收到这些错误消息,并且测试用例失败:

Wanted but not invoked:
enrollRepository.delete(
    Enroll{id=1, eCondition='Normal', eRemarks='null', ebStartdt='2019-04-09T16:40:32.703Z[UTC]', ebEnddt='2019-04-09T16:40:32.703Z[UTC]', eDate='2019-04-09T16:40:32.703Z[UTC]'}
);
-> at com.team.generated.service.EnrollServiceTest.testDeleteEnrollExpectSuccess(EnrollServiceTest.java:61)

However, there was exactly 1 interaction with this mock:
enrollRepository.deleteById(1L);
-> at com.team.generated.service.EnrollService.delete(EnrollService.java:74)

有什么主意吗?谢谢!

1 个答案:

答案 0 :(得分:0)

错误说明了一切:您正在验证方法delete(Long id)

verify(enrollRepository, times(1)).delete(enroll);

但是,您的服务对象会调用deleteById()方法:

enrollRepository.deleteById(id);

我认为您想这样做:

@Test
public void testDeleteEnrollExpectSuccess() {
    Enroll enroll = prepareEnrollWithBedAllocation();
    enrollService.delete(enroll.getId());
    verify(enrollRepository, times(1)).deleteById(enroll.getId());
}