Reputation: 265
I have the following Service class with dynamic query.
public class CarService {
public Page<Cars> getAllCars(CarRequest request, ,, String carCarrier, String carNumber,Pageable pageRequest){
String userCarrier = request.getSubCarrier();
Specification <Car> carSpecification = null;
carSpecification = getCarDetails(request, carCarrier, carNumber);
return carRepository.findAll(carSpecification, pageRequest);
}
public Specification<Car> getCarDetails(CarRequest request, String carCarrier, String carNumber) {
System.out.println("I am in query");
return (Root<Car> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
System.out.println("I am executing query");
List<Predicate> predicates = new ArrayList<>();
if(StringUtils.isNotBlank(request.getCarColor())) {
predicates.add(cb.and(cb.equal(root.get(“carColor”), request.getCarColor())));
}
if(StringUtils.isNotBlank(carCarrier)) {
predicates.add(cb.and(root.get("carCarrier”),carCarrier)));
}
if(StringUtils.isNotBlank(carNumber)) {
predicates.add(cb.and(cb.equal(root.get("carNumber"), carNumber)));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
}
}
Below is my Test class where i am trying to test the dynamic query.
public class CarServiceTest {
@Mock
private CarService carService;
@Test
public void test_cars() {
Pageable pageRequest = new PageRequest(0,20);
CarRequest request = new CarRequest();
request.setCarColor(“Red”);
request.setCarMake(“Nissan”);
when(carRepository.findAll(Mockito.any(Specification.class), Mockito.eq(pageRequest)))
.thenReturn(Mockito.mock(Page.class));
Assert.assertNotNull(carService.getAllCars(request, pageRequest));
}
}
The above test case works but it just enters getCarDetails and prints the first line " I am in query" and returns. It does not go further ahead to check the conditional clauses in the query.
I also tried calling the method directly from test class as
carService.getCarDetails(carRequest. "ABC", “A123”);
Still the same result. I have recently started with Mockito so i am not sure if i am missing something here which is causing this behavior.
How can i make sure all my lines are executed from code coverage perspective.
Upvotes: 0
Views: 1290
Reputation: 2366
Specification
is functional interface and you returning function which will be called by spring under the hood (after when you pass it to suitable repository method). In test you mock that repostiory method so there is no chance to execute that returned function.
In Specification
case this function is called toPredicate()
Upvotes: 1