Felipe Fernández
Felipe Fernández

Reputation: 311

Generate MailSendException with fake smtp server

I need to test some component that sends an email batch using a Spring MailSender instance. The method "send" throws a MailSendException when the provided destination address is not well formed, something like myAddressgmail.com (Note that I'm not pretending that my smtp server know if the address really exist in the destination host, just talking about structure). In fact, this is what happens when using my real smtp server.

To mock the smtp server I've tried Dumbster and GreenMail and here appears the problem. These fake smtp servers don't check if the address is well formed, so the MailSendException is not thrown. I need to throw this exception in order to test the exception handling.

Upvotes: 1

Views: 1204

Answers (2)

Anish John
Anish John

Reputation: 410

You can use mailnest.io for your email testing. In the platform there is an error mode which you can switch on to mock an error response from the server.

Upvotes: 0

matt b
matt b

Reputation: 139931

Use a mocking library like Mockito or EasyMock.

Then you can do something like:

MailSender mockSender = mock(MailSender.class);
YourSMTPServer server = new YourSMTPServer(mockSender);

when(mockSender.send(...)).thenThrow(new MailSendException(...));

// then invoke the method on your server that calls MailSender.send() and
// assert it does what you want it to do when an exception is encountered

Upvotes: 2

Related Questions