【发布时间】: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