Test method

public boolean delete(Long id) { Message message = messageRepository.findOne(id); if (message == null) { throw new DataNotFoundException("Data with id=" + id + " not found."); } messageRepository.delete(id); return true; } 

Test:

 @Test public void delete() throws Exception { //prepare MessageServiceImp spy = spy(new MessageServiceImp(messageRepository)); messageServiceImp.save(MESSAGE); //создаю объект, пробовал и не создавать результат одинаков doReturn(true).when(spy).delete(ID); //testing boolean testMessage = messageServiceImp.delete(ID); //validate verify(messageRepository).delete(ID); } 

Test fails get:

.exception.DataNotFoundException: Data with id = 1 not found.

What am I doing wrong?


Add MessageRepository

 public interface MessageRepository extends JpaRepository<Message, Long>{ } 
  • What are you trying to test? describe your test with words. - Mikhail Vaysman
  • I want to check that the delete method, getting an id, will delete and return true. - Sergei R

1 answer 1

Here is my option.

Test method

 public void delete(Long id) { // так делать плохо // добавлено по просьбе вопрошающего try { // проверку на существование и пр. должен делать MessageRepository messageRepository.delete(id); } catch(EmptyResultDataAccessException ex) { throw new DataNotFoundException("Data with id=" + id + " not found."); } } 

Test

 private static final Long ID = 123; // интерфейс, а не реализация private MessageRepository messageRepository; @Test public void detele_delegateToRepository() throws Exception { // подготовка messageRepository = mock(MessageRepository.class); // не знаю как у вас класс называется - будем считать Subject Subject subject = new Subject(messageRepository); // действие subject.delete(ID); // проверка verify(messageRepository).delete(ID); } @Test(expected = DataNotFoundException.class) public void detele_throwsException() throws Exception { // подготовка messageRepository = mock(MessageRepository.class); // не знаю как у вас класс называется - будем считать Subject Subject subject = new Subject(messageRepository); when(messageRepository.delete(ID)).thenThrow(new EmptyResultDataAccessException()); // действие subject.delete(ID); } 

This is all you need to test. The rest of the tests should be for the class that implements the MessageRepository.

  • boolean and return messageRepository.delete (id); == Incompatible types. - Sergei R
  • show your MessageRepository - Mikhail Vaysman
  • Added higher in the body of the question. - Sergei R
  • @SergeiR fixed the code - Mikhail Vaysman
  • Well, is there a check if such an id? I have it here before calling messageRepository.delete (id); - Sergei R