为了账号安全,请及时绑定邮箱和手机立即绑定

Spring JPA 规范 API 的 Mockito 不完全执行动态查询

Spring JPA 规范 API 的 Mockito 不完全执行动态查询

PIPIONE 2023-08-09 16:08:47
我有以下带有动态查询的服务类。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()]));        };    }}下面是我的测试类,我正在尝试测试动态查询。public class CarServiceTest {@Mockprivate CarService carService;@Testpublic 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));    }}上面的测试用例有效,但它只是输入 getCarDetails 并打印第一行“我正在查询”并返回。它不会进一步检查查询中的条件子句。我还尝试直接从测试类调用该方法carService.getCarDetails(carRequest. "ABC", “A123”);结果还是一样。我最近开始使用 Mockito,所以我不确定我是否在这里遗漏了导致此行为的某些内容。我如何确保我的所有行都从代码覆盖率的角度执行。
查看完整描述

1 回答

?
慕妹3242003

TA贡献1824条经验 获得超6个赞

Specification是函数式接口,您返回的函数将由 spring 在后台调用(当您将其传递给合适的存储库方法之后)。在测试中,您模拟该存储库方法,因此没有机会执行该返回的函数。

如果Specification调用此函数toPredicate()

查看完整回答
反对 回复 2023-08-09
  • 1 回答
  • 0 关注
  • 100 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信