【发布时间】:2021-11-21 17:32:28
【问题描述】:
我目前使用 Spring Boot 设计一个 API。在我的服务层中,我使用实体管理器来访问数据库。我在下面的服务层中提供了一个方法作为示例。
public Object getFirstReturnDate(Long vehicle_id, LocalDateTime reservation_date){
String string = "SELECT r.reservation_time from Reservation r left join fetch r.driverAssignment where r.reservation_time > :reservation_time " +
"and r.reserved_status.slug in ('pending','approved') and r.reserved_vehicle.id=:vehicle_id " +
" order by r.reservation_time asc ";
Query query = em.createQuery(string);
query.setParameter("reservation_time",reservation_date);
query.setParameter("vehicle_id",vehicle_id);
List<LocalDateTime> localDateTimes=query.getResultList();
if(localDateTimes.size()==0)
return new DefaultResponseDTO(200, ResponseStatus.OK,"Any Date",null);;
return new DefaultResponseDTO(200, ResponseStatus.OK,"Possible Time",localDateTimes.get(0));
}
在测试单元中,我将实体管理器模拟如下,
@Mock
EntityManager em;
而在测试方法中,
Query query = Mockito.mock(Query.class);
Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query);
Mockito.when(query.getResultList()).thenReturn(new LinkedList());
我的问题是,如果我像上面提到的那样模拟实体 Manger,那么方法中的查询不会被检查。这是一种糟糕的编码习惯吗?
有没有其他方法可以在不调用数据库的情况下检查查询?
【问题讨论】:
标签: spring-boot unit-testing mocking entitymanager