MailSenderAdapter { @Scheduled(fixedDelay = 10000L) @Transactional public void sendPendingMessages() { messageRepository.findAll().forEach(templateMessage -> { try { if(templateMessage.isStillRelevant(LocalDateTime.now(clock))) { sendMessage(templateMessage); } messageRepository.delete(templateMessage); } catch (Exception err) { log.error("Error sending mail!", err); } }); } MailSenderAdapter(MessageRepository messageRepository,
                             JavaMailSender mailSender,
                             UserService userService,
                             MailConfigurationProperties properties,
                             Clock clock); @Scheduled(fixedDelay = 10000L) @Transactional void sendPendingMessages(); @Transactional T queueMessage(T message);  }
@Test public void sendPendingMessagesOnlySendsRelevantMessages() { var expectedFrom = "sender@test.com"; var expectedTo = "email@test.com"; var expectedSubject = "This is a subject!"; var expectedText = "This is a long text!"; var expectedSimpleMessage = new SimpleMailMessage(); expectedSimpleMessage.setFrom(expectedFrom); expectedSimpleMessage.setTo(expectedTo); expectedSimpleMessage.setSubject(expectedSubject); expectedSimpleMessage.setText(expectedText); given(messageRepositoryMock.findAll()).willReturn(List.of(templateMessageMock, templateMessageMock)); given(templateMessageMock.isStillRelevant(LocalDateTime.now(clock))) .willReturn(false, true); given(templateMessageMock.getSubject()).willReturn(expectedSubject); given(templateMessageMock.getText()).willReturn(expectedText); given(templateMessageMock.getAddressee()).willReturn(userMock); given(userServiceMock.getUserData(userMock)).willReturn(userDataMock); given(userDataMock.getEmail()).willReturn(expectedTo); given(mailPropertiesMock.getFromMail()).willReturn(expectedFrom); mailSenderAdapter.sendPendingMessages(); verify(messageRepositoryMock, times(2)).delete(templateMessageMock); verify(javaMailSenderMock).send(expectedSimpleMessage); }