2

我正在尝试为使用 Querydsl (Mysema) 库的 Spring Boot 应用程序的方法设置单元测试。要测试的方法包括以下几行代码:

JPAQueryFactory queryFactory = new JPAQueryFactory(em);
QEntity q = QEntity.entity;

long count = queryFactory.from(q)
    .select(q.anInteger)
    .where(aBooleanExpression)
    .fetchCount();

在单元测试类中,我正在编写一个用@Before注释的设置方法,其中我执行以下操作:

    JPAQueryFactory queryFactory = Mockito.mock(JPAQueryFactory.class, Mockito.RETURNS_DEEP_STUBS);

    QEntity q = QEntity.etity;
    BooleanExpression aBooleanExpression = ... // The same as used in the method under test

    Mockito
        .when(((JPAQuery<Integer>) queryFactory
                .from(q)
                .select(q.anInteger))
                .where(aBooleanExpression)
                .fetchCount()
        ).thenReturn(1L);

没有编译错误,但是当我运行测试时出现异常:

java.lang.ClassCastException: com.querydsl.core.support.QueryBase$$EnhancerByMockitoWithCGLIB$$6824f47d cannot be cast to com.querydsl.jpa.impl.JPAQuery

我不知道我必须以哪种方式对以前的代码进行处理才能使其正常工作。

4

2 回答 2

1

每个调用返回对象

queryFactory.from(q)
            .select(q.anInteger))
            .where(aBooleanExpression)
            .fetchCount()

在您的情况下,您应该逐步模拟:

 JPAQuery step1 = Mockito.mock(JPAQuery.class);
 Mockito.when(queryFactory.from(q)).thenReturn(step1);
 JPAQuery step2 = Mockito.mock(JPAQuery.class);
 Mockito.when(step1.select(q.anInteger)).thenReturn(step2);
 JPAQuery step3 = Mockito.mock(JPAQuery.class);
 Mockito.when(step2.where(aBooleanExpression)).thenReturn(step3);

... 等等

不确定返回对象类请检查,它只是用于解释的示例。

于 2018-05-25T04:28:05.113 回答
0

我遇到了 Springboot unitest 这个问题,我的查询是

List<TaxiEntity> taxiEntities = queryFactory.selectFrom(qTaxiEntity)
            .innerJoin(qTaxiEntity.callMe, qDriver)
            .where(qTaxiEntity.abcId.eq(abcId))
            .limit(pageable.getPageSize())
            .offset(pageable.getOffset())
            .fetch();

我模拟这个查询的单元测试是。它运行成功

    @Mock
    private JPAQueryFactory queryFactory;

    @Test
    public void testBanana() {
    .....
    JPAQuery jpaQuery = Mockito.mock(JPAQuery.class);
    when(queryFactory.selectFrom(any())).thenReturn(jpaQuery);
    when(jpaQuery.select(any(Expression.class))).thenReturn(jpaQuery);
    when(jpaQuery.innerJoin((EntityPath) any(), any())).thenReturn(jpaQuery);
    when(jpaQuery.where(any(BooleanExpression.class))).thenReturn(jpaQuery);
    when(jpaQuery.limit(anyLong())).thenReturn(jpaQuery);
    when(jpaQuery.offset(anyLong())).thenReturn(jpaQuery);
    when(jpaQuery.fetch()).thenReturn(resultList);
    ....
    }
于 2021-09-06T11:09:27.710 回答