【问题标题】:How to mock joins in queryDsl (jpa + mockito)?如何在queryDsl(jpa + mockito)中模拟连接?
【发布时间】:2021-10-08 19:37:09
【问题描述】:

给定通过加入实体从实体中选择的 queryDsl 代码

@Repository
@RequiredArgsConstructor
public class BlahRepository {

  private final JPAQueryFactory jpaQueryFactory;

  public List<YyzPerEntity> getYyzPerById(Long id) {

    final QYyzPerEntity n = YyzPerEntity;
    final QDufEntity d = dufEntity;
    final QWofEntity g = wofEntity;

    return jpaQueryFactory
      .selectFrom(n)
      .leftJoin(d)
      .on(n.pLnr.eq(d.dufEntityPK.dofx))
      .leftJoin(g)
      .on(d.wof.getID().eq(g.Id))
      .where(g.Id.eq(Id))
      .fetch();
  }

我想模拟连接部分:

@Mock private JPAQueryFactory queryFactory;
private JPAQuery queryMock;
@InjectMocks private BlahRepository blahRepository;

@Test
  void byId() {
    // arrange
    queryMock = mock(JPAQuery.class);
  when(queryFactory.selectFrom(QYyzPerEntity.yzPerEntity))
  .thenReturn(queryMock);
 // how to mock joins here... ? 
  when(queryMock.fetch()).thenReturn(List.of(QYyzPerEntity.yzPerEntity));

  // act
  List<YyzPerEntity> yyzPerById =
  blahRepository.getYyzPerById(123L);

  // assert
  assertThat(yyzPerById).isNotNull();

有什么我可以尝试的想法吗?

我得到的错误是:

 java.lang.NullPointerException: Cannot invoke com.querydsl.jpa.impl.JPAQuery.on(...) because the return value of com.querydsl.jpa.impl.JPAQuery.leftJoin(com.querydsl.core.types.EntityPath) is null

是完全有可能还是不能被嘲笑?

【问题讨论】:

  • 你为什么要模拟JPAQuery?此时,您要么测试 Querydsl 的内部结构,要么确保您编写了您所写的内容。只需模拟整个 blahRepository 即可。如果您想正确测试blahRepository,最好在实际执行针对数据库的查询的集成测试中这样做。也可以使用querydsl-collections 对模拟数据执行查询。

标签: java jpa mocking mockito querydsl


【解决方案1】:

模拟构建器 API(例如 JPAQuery)的最简单方法是使用 Answers.RETURNS_SELF 作为默认存根。

例如,使用以下代码来实例化您的queryMock

@Mock(answer = Answers.RETURNS_SELF) JPAQuery queryMock;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2021-12-10
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多