我在项目https://github.com/JonkiPro/popcorn/blob/master/core/src/main/java/com/core/jpa/specification/MessageSpecs.java#L30中创建了规范,问题在于片段
if (Optional.ofNullable(subject).isPresent()) {
predicates.add(cb.like(cb.upper(root.get(MessageEntity_.subject)), "%" + subject.toUpperCase() + "%"));
}
if (Optional.ofNullable(text).isPresent()) {
predicates.add(cb.like(cb.upper(root.get(MessageEntity_.text)), "%" + text.toUpperCase() + "%"));
}
当我写测试时
final Path<String> subjectPath = (Path<String>) Mockito.mock(Path.class);
final Predicate likeSubjectPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(MessageEntity_.subject)).thenReturn(subjectPath);
Mockito.when(this.cb.like(subjectPath, SUBJECT)).thenReturn(likeSubjectPredicate);
final Path<String> textPath = (Path<String>) Mockito.mock(Path.class);
final Predicate likeTextPredicate = Mockito.mock(Predicate.class);
Mockito.when(this.root.get(MessageEntity_.text)).thenReturn(textPath);
Mockito.when(this.cb.like(subjectPath, TEXT)).thenReturn(likeTextPredicate);
并测试
final Specification<MessageEntity> spec = MessageSpecs.findSentMessagesForUser(USER, SUBJECT, TEXT);
spec.toPredicate(this.root, this.cq, this.cb);
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.cb.upper(this.root.get(MessageEntity_.subject)), "%" + SUBJECT.toUpperCase() + "%");
Mockito
.verify(this.cb, Mockito.times(1))
.like(this.cb.upper(this.root.get(MessageEntity_.text)), "%" + TEXT.toUpperCase() + "%");
它崩溃了异常
org.mockito.exceptions.verification.TooManyActualInvocations:
criteriaBuilder.upper(
Mock for Path, hashCode: 647973805
);
Wanted 1 time:
-> at com.jonki.popcorn.core.jpa.specification.MessageSpecsUnitTests.testFindAllSentMessagesForUser(MessageSpecsUnitTests.java:72)
But was 2 times. Undesired invocation:
-> at com.jonki.popcorn.core.jpa.specification.MessageSpecs.lambda$findSentMessagesForUser$af9d022e$1(MessageSpecs.java:44)
如果我使用GitHub编辑此方法,我将从一个对象中删除upper()
方法,例如第一个subject
predicates.add(cb.like(root.get(MessageEntity_.subject), "%" + subject.toUpperCase() + "%"));
predicates.add(cb.like(cb.upper(root.get(MessageEntity_.text)), "%" + subject.toUpperCase() + "%"));
此测试正确显示没有任何错误。
该错误导致upper()
方法用于两个对象。这里发生了什么?为什么会这样?