I currently design an API using spring boot. In my service layer, I use Entity Manager for accessing the database. I have provided a method in my service layer below as an example.
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));
}
in the testing unit, I mocked the entity manager as below,
@Mock
EntityManager em;
And in the test method,
Query query = Mockito.mock(Query.class);
Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query);
Mockito.when(query.getResultList()).thenReturn(new LinkedList());
My question is, if I mock entity Manger as I mentioned above then the query in the method didn't get checked. Is it a bad coding practice?
Is there any other way to check queries without calling the database?
CodePudding user response:
Any testing approach should be part of a comprehensive testing strategy. I.e. you should know which types of bugs you expect your unit tests to find, which types of bugs you expect integration and E2E tests to find, etc.
Mocking an EntityManager has pros:
- It is easier to test your business logic in isolation
- You can set up hypothetical scenarios with ease
- Your tests will be much faster as you don't establish a connection to the database
But also cons:
- You do not test your database connection and configuration
So the question is, where are you testing for database integration issues if they are not check in this test? Once you know the answer to that question you will know the answer to the one you have asked above.
I would recommend reviewing the "Testing Strategies in a Microservice Architecture" for a more in-depth view of how to approach your testing.