'Unable to unit test a spring service calling mocked custom repository
I defined a custom repository Interface which get stream of entities through Query.getResultStream
public interface MyRepository<T> {
Stream<T> findByCriteria(...);
}
public class MyRepositoryImpl<T> implements MyRepository<T> {
@Autowired SessionFactory sessionFactory;
public Stream<T> findByCriteria(...) {
...
}
}
and my Repository & Service
@Repository
public interface EntityRepository extends MyRepository<Entity> {
...
}
@Service
@Transactional(readOnly = true)
public class EntityService {
@Autowired EntityRepository entityRepository;
public Stream<Entity> getEntitiesByCriteria(String criteria) {
...
return entityRepository.findByCriteria(...);
}
}
Problem is my Service Unit Test does not see the repository implementation, and always return null without going inside findByCriteria implementation.
ExtendWith(MockitoExtension.class)
class EntityServiceTest {
@InjectMocks EntityService service;
@Mock EntityRepository repository;
@Test
void test() {
...
when(repository.findByCriteria(...))
.thenReturn(...);
service.getEntitiesByCriteria(...); //This does not see the implementation of findByCriteria in MyRepositoryImpl
]
}
I tried many annotations like @RepositoryDefinition in my interface or @EnableJpaRepositories in my test class but nothing seems to work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
