Java Junit、Mockito和Querydsl(Mysema)用于模拟JPAQueryFactory
我正在尝试为使用Querydsl(Mysema)库的Spring引导应用程序的方法设置一个单元测试。 要测试的方法包括以下代码行:Java Junit、Mockito和Querydsl(Mysema)用于模拟JPAQueryFactory,java,junit,mockito,querydsl,mysema,Java,Junit,Mockito,Querydsl,Mysema,我正在尝试为使用Querydsl(Mysema)库的Spring引导应用程序的方法设置一个单元测试。 要测试的方法包括以下代码行: JPAQueryFactory queryFactory = new JPAQueryFactory(em); QEntity q = QEntity.entity; long count = queryFactory.from(q) .select(q.anInteger) .where(aBooleanExpression) .fetc
JPAQueryFactory queryFactory = new JPAQueryFactory(em);
QEntity q = QEntity.entity;
long count = queryFactory.from(q)
.select(q.anInteger)
.where(aBooleanExpression)
.fetchCount();
在单元测试类中,我正在编写一个在之前用@注释的设置方法,在这里我执行以下操作:
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);
我不知道我必须以何种方式使用前面的代码才能使其工作。每个调用返回对象
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);
。。。等等
不确定返回对象类,请检查,这只是一个示例,仅供解释
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);