### Question:
MessageServiceImpl implements MessageService { @Transactional @Override public Message add(MessageDto messageDto) { int minlength = 3; if (messageDto.getName().length() < 3) { throw new RuntimeException(String.format("Message name should be at least %s characters long", minlength)); } if (repository.findByTypeAndName(messageDto.getType(), messageDto.getName()).isPresent()) { throw new RuntimeException(String.format("Message with type %s and name %s already exists", messageDto.getType().toString(), messageDto.getName())); } Message newM = objectMapper.convertValue(messageDto, Message.class); return repository.save(newM); } MessageServiceImpl(MessageRepository repository, ObjectMapper objectMapper); @Transactional(readOnly = true) @Override List<MessageDto> getMessagesByType(MessageType type); @Override MessageDto getMessageByKey(String key); @Override MessageDto getMessageByTypeAndName(MessageType type, String name); @Transactional @Override Message update(MessageDto messageDto); @Transactional @Override Message add(MessageDto messageDto); @Transactional @Override void delete(MessageType type, String name);  }### Answer:
@Test void add() { Message message = Message.builder().type(MessageType.REFERRAL_SHARE).name("myNewItem").build(); MessageDto messageDto = MessageDto.builder().type(MessageType.REFERRAL_SHARE).name("myNewItem").build(); when(objectMapper.convertValue(messageDto, Message.class)).thenReturn(message); when(messageRepository.save(message)).thenReturn(message); Message result = messageService.add(messageDto); assertThat(result).isEqualTo(message); }
@Test void add_throwsExceptionWhenExists() { try { messageService.add(messageDto1); failBecauseExceptionWasNotThrown(RuntimeException.class); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo(String.format("Message with type %s and name %s already exists", messageDto1.getType().toString(), messageDto1.getName())); } }
@Test void add_throwsExceptionWhenNameIsToShort() { MessageDto messageDto = MessageDto.builder().type(MessageType.REFERRAL_SHARE).name("m1").build(); try { messageService.add(messageDto); failBecauseExceptionWasNotThrown(RuntimeException.class); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("Message name should be at least 3 characters long"); } }