【问题标题】:Is it a good practice to Mock entity manager in spring boot unit testing在 Spring Boot 单元测试中模拟实体管理器是一个好习惯吗
【发布时间】: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


    【解决方案1】:

    任何测试方法都应该是综合测试策略的一部分。 IE。您应该知道您希望您的单元测试找到哪些类型的错误,您希望集成和 E2E 测试找到哪些类型的错误等。

    模拟 EntityManager 有优点:

    • 单独测试业务逻辑更容易
    • 您可以轻松设置假设场景
    • 您的测试会更快,因为您不建立与数据库的连接

    但也有缺点:

    • 您没有测试您的数据库连接和配置

    所以问题是,如果没有在此测试中检查数据库集成问题,您将在哪里测试它们?一旦您知道了该问题的答案,您就会知道您在上面提出的问题的答案。

    我建议您查看“Testing Strategies in a Microservice Architecture”,以更深入地了解如何进行测试。

    【讨论】:

      猜你喜欢
      • 2011-01-06
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2016-01-03
      • 2019-07-17
      • 2010-11-25
      • 1970-01-01
      • 2012-09-12
      相关资源
      最近更新 更多