我试图编写junit for repository接口,但不知何故它出现了问题。
我的界面:
@Repository
public interface SampleRepository extends JpaRepository<SampleEntity, Long>, JpaSpecificationExecutor<SampleEntity> {
@EntityGraph(attributePaths = { "SamplsHistory"}, type = EntityGraph.EntityGraphType.LOAD)
public List<TestEntity> findAll(Specification<TestEntity> spec);
public static Specification<SamplsEntity> fetchSamplssSpecification(SampleSearchCriteria criteria) {
return (rootEntity, cq, cb) -> {
List<Predicate> predicates = new ArrayList<>();
**if (CollectionUtils.isNotEmpty(criteria.getIds())) {
In<Long> inId = cb.in(rootEntity.get(SamplConstants.Sampls_ID));
criteria.getIds().forEach(inId::value);
predicates.add(inId);
}
if (StringUtils.isNotEmpty(criteria.getSearchText())) {
Predicate apName= cb.like(rootEntity.get(SampleConstants.Sampls_NAME), "%" + criteria.getSearchText() + "%");
predicates.add(cb.or(apName));
}**
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
我尝试为此编写junit,但无法做到这一点>
我的界面:
@RunWith(MockitoJUnitRunner.class)
class SampleRepositoryTest {
private Root<SampleEntity> root;
private CriteriaQuery<?> cq;
private CriteriaBuilder cb;
@InjectMocks
private SampleRepository SampleRepository;
@InjectMocks
private SampleEntity SampleEntity;
private static final String SEARCH_TERM_LIKE_PATTERN = "test%";
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this.getClass());
SampleRepository = mock(SampleRepository.class);
cb = mock(CriteriaBuilder.class);
cq = mock(CriteriaQuery.class);
root = (Root<SampleEntity>) Mockito.mock(Root.class);
}
@Test
void fetchSamplesSpecification() {
SampleSearchCriteria criteria = mock(SampleSearchCriteria.class);
criteria.setSearchText("Marsh");
Specification<SampleEntity> spec = (Specification<SampleEntity>) Mockito.mock(Specification.class);
//when(SampleRepository.fetchSamplesSpecification(criteria)).thenReturn(spec);
Predicate SampleNameIsLikePredicateMock = mock(Predicate.class);
when(cb.like(root.get(AccountConstants.Sample_NAME), SEARCH_TERM_LIKE_PATTERN))
.thenReturn(SampleNameIsLikePredicateMock);
when(spec.toPredicate(root, cq, cb)).thenReturn(SampleNameIsLikePredicateMock);
verify(root, times(1)).get(SampleConstants.Sample_NAME);
verifyNoMoreInteractions(root);
// verify(cb, times(1)).like(root.get(SampleConstants.Sample_NAME),
// SEARCH_TERM_LIKE_PATTERN);
verifyNoMoreInteractions(cb);
}
}
}
请检查以上内容,了解junit是否正确。此外,当我尝试代码覆盖率没有显示也junit是不成功的。
注意:需要介绍junit for存储库。
暂无答案!
目前还没有任何答案,快来回答吧!