Я новичок в Spring Boot и Mockito, и у меня возникла проблема с вызовом репозитория в моем сервисном тесте.
У меня есть вызов метода «delete» службы следующим образом, который я пытаюсь протестировать с помощью Mockito путем макетирования вызовов репозитория:
public interface IEntityTypeService {
public EntityType getById(long id);
public EntityType getByName(String name);
public List<EntityType> getAll();
public void update(EntityType entityType);
public void delete(long id);
public boolean add(EntityType entityType);
}
@Service
public class EntityTypeServiceImpl implements IEntityTypeService {
@Autowired
private EntityTypeRepository entityTypeRepository;
@Override
public void delete(long id) {
entityTypeRepository.delete(getById(id));
}
@Override
public EntityType getById(long id) {
return entityTypeRepository.findById(id).get();
}
....implementation of other methods from the interface
}
Мой репозиторий выглядит следующим образом:
@RepositoryRestResource
public interface EntityTypeRepository extends LookupObjectRepository<EntityType> {
}
Я не реализовал ни один из методов в репозитории, так как позволяю Spring Boot подключить его для меня.
Мой тест выглядит следующим образом:
@RunWith(SpringRunner.class)
public class EntityTypeServiceTest {
@TestConfiguration
static class EntityTypeServiceImplTestContextConfiguration {
@Bean
public IEntityTypeService entityTypeService() {
return new EntityTypeServiceImpl();
}
}
@Autowired
private IEntityTypeService entityTypeService;
@MockBean
private EntityTypeRepository entityTypeRepository;
@Test
public void whenDelete_thenObjectShouldBeDeleted() {
final EntityType entity = new EntityType(1L, "new OET");
Mockito.when(entityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);
// when
entityTypeService.delete(entity.getID());
// then
Mockito.verify(entityTypeRepository, times(1)).delete(entity);
assertThat(entityTypeRepository.findById(1L).get()).isNull();
}
}
Когда я запускаю тест, я получаю сообщение об ошибке «java.util.NoSuchElementException: значение отсутствует»
java.util.NoSuchElementException: No value present
at java.util.Optional.get(Optional.java:135)
at xyz.unittests.service.EntityTypeServiceTest.whenDelete_thenObjectShouldBeDeleted(OriginatingEntityTypeServiceTest.java:41)
Ссылка на строку в тесте говорит: Mockito.when(originatingEntityTypeRepository.findById(1L).get()).thenReturn(entity).thenReturn(null);
ПричинаЯ думаю, что мне нужно высмеять этот вызов, потому что метод delete в Сервисе вызывает метод getById () в той же службе, которая, в свою очередь, вызывает entityTypeRepository.findById (id) .get ()
то, что я предполагаю, что я должен издеваться над удалением.Но явно я не прав.Любая помощь будет оценена.
Большое спасибо