How to test JavaMailSender?

spring-boot test javamailsender
javamailsender mock
junit test case for sending email
javamailsender and transport
spring boot listening for incoming emails
mockito test email service
spring boot mail receiver example
javamailsender jar

I have little problem. I created MailService to send mails. When I run program, it works. All properties to email I have in resources/application.properties. I'm using spring-boot-starter-mail.

@Service
public class MailService {
    private JavaMailSender javaMailSender;

    @Autowired
    public MailService(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    public void sendMail(String subject, String messageContent, String recipient)
            throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setTo(recipient);
        messageHelper.setSubject(subject);
        messageHelper.setText(messageContent);
        javaMailSender.send(mimeMessage);
    }
}

But I don't have idea how can I create test for it. I tried something like this, where I use org.jvnet.mock-javamail:mock-javamail, but it doesn't work:

public class MailServiceTest {
    private MailService mailService;

    @Mock
    private JavaMailSender javaMailSender;


    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mailService = new MailService(javaMailSender);
        Mailbox.clearAll();
    }

    @Test
    public void sendMailTest() throws MessagingException, IOException {
        String subject = "Some subject";
        String body = "Some contents.";
        String recipient = "test@test.com";

        mailService.sendMail(subject, body, recipient);
        List<Message> inbox = Mailbox.get(recipient);
        assertTrue(inbox.size() == 1);
        assertEquals(subject, inbox.get(0).getSubject());
        assertEquals(body, inbox.get(0).getContent());
    }
}

How to test JavaMailSender?, I think you are getting unit test / mocking wrong. It seems that you want to create a unit test; but expect the results of a integration test. What you� A JavaMailSender client is not as easy to test as a plain MailSender client, but still straightforward compared to traditional JavaMail code: Just let createMimeMessage () return a plain MimeMessage created with a Session.getInstance (new Properties ()) call, and check the passed-in messages in your mock implementations of the various send methods.

You can test how MimeMessage was formed with:

public class EmailServiceTest {

    private EmailServiceImpl emailServiceImpl;

    private JavaMailSender javaMailSender;

    private MimeMessage mimeMessage;

    @Before
    public void before() {
        mimeMessage = new MimeMessage((Session)null);
        javaMailSender = mock(JavaMailSender.class);
        when(javaMailSender.createMimeMessage()).thenReturn(mimeMessage);
        emailServiceImpl = new EmailService(javaMailSender);
    }

    @Test
    public void emailTest() {
        String recipient = "example@example.com"
        EmailRequest request = new EmailRequest();
        request.setRecipient(recipient);
        emailServiceImpl.send(request);
        assertEquals(recipient, mimeMessage.getRecipients(RecipientType.TO)[0].toString());
    }
}

JavaMailSender, production implementation is JavaMailSenderImpl ; for testing, mocks can be created based on this interface. Clients will typically receive the JavaMailSender � assertEquals (body, inbox.get (0).getContent ()); } } First Test uses the regular Javamail approach for reading the mail and the other one uses the Mock-JavaMail approach to read the mails from the Mock Email Server.

I use Mockito to mock a JavaMailSender bean and instantiate it in a class annotated with @Configuration that runs only using a test profile:

import static org.mockito.Mockito.*;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import org.springframework.context.annotation.*;
import org.springframework.mail.javamail.JavaMailSender;

@Profile("test")
@Configuration
public class EmailServiceTest {
    @Bean
    @Primary
    public JavaMailSender javaMailSender() {
        JavaMailSender javaMailSender = mock(JavaMailSender.class);
        when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));
        return javaMailSender;
    }
}

EmailServiceTest.java, Verify newly registered users by sending them a verification token via JavaMailSender interface: the subinterface of the above MailSender. ContentsI. TechnologiesII. Practice1. Create SpringBoot project2. Create MailSender3. Develop a test client4. Run & check resultsIII. Sourcecode I. Technologies – Java 1.8 – Maven … Continue reading "How to configure JavaMailSender with SpringBoot"

You can use greenmail http://www.icegreen.com/greenmail instead of mocking a email server

@Test
public void test_MyMailSend() {
    GreenMail greenMail = new GreenMail(ServerSetupTest.SMTP_IMAP);
    try {
        greenMail.start();
        //your class method call goes her 
        assertTrue(greenMail.waitForIncomingEmail(5000, 1));
        //Retrieve using GreenMail API
        Message[] messages = greenMail.getReceivedMessages();
        final String subject = messages[0].getSubject();
        final String msgContent = messages[0].getContent().toString();
        assertEquals(1, messages.length);
        assertEquals(subject, MyClass.SUPPORT_SUBJECT);
        assertEquals(messages[0].getAllRecipients()[0].toString(), MyClass.SUPPORT_ADDRESS);
        assertEquals(messages[0].getFrom()[0].toString(), MyClass.FROM_EMAIL);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        greenMail.stop();
    }
}

Guide to Spring Email, private static class MockJavaMailSender extends JavaMailSenderImpl { private MockTransport transport; protected Transport getTransport(Session session)� 2. JavaMailSender and Email templates 2.1. Java Configuration. Given is Java configuration for JavaMailSender which has been configured to use Gmail SMTP settings and we have configured a sample email template preconfigured with sender/reciever emails and email text. You can customized the configuration as per your need.

Spring Framework example, But how to test that mail configuration and submission is working fine? Support (if not present) that contains JavaMailSender support class. In this tutorial we demonstrate how to send a simple email using spring mail and spring boot. First we configure our email properties using a YAML or props.

Mocked JavaMailSender in EmailServiceTest (05f2bf34) � Commits , JavaMailSender. The following examples show how to use org.springframework. mail.javamail.JavaMailSender. These examples are extracted from open source � This tutorial will show you how to send a basic mail via Spring framework’s email support. A class that comes in pretty handy when dealing with JavaMail messages is the org.springframework.mail.javamail.MimeMessageHelper class, which shields you from having to use the verbose JavaMail API.

Testing mail code in Spring Boot application, Spring Mail Integration Testing with JUnit and GreenMail Example JavaMailSender emailSender; public void sendSimpleMessage(Mail� Finally, we can start writing our Integration Test. @SpringBootTest – specifies that the unit tests is a spring boot based test and configures appropriately. @ActiveProfiles("test") – specifies that the profile test is used to run the tests. @RunWith(SpringRunner.class) – specifies that JUnit will run the tests with the SpringRunner class.

Comments
  • What means but it doesn't work?
  • What is MailBox --- where is that coming from in your test code?!
  • Mailbox is from import org.jvnet.mock_javamail.Mailbox;.
  • Thanks, but I still have little problem. I don't know how to verify this mock.
  • I found in Google how to use verify on mock and it works :D Thanks for your help.
  • You are very welcome. Please consider accepting my answer then.