Mocking Mail API in Scala

Few days ago I was working on a Mailing API of my project and used javax-mail API but encountered the problem of how to write unit test cases for that without actually mocking the mail. I searched for it but was unable to find a proper documentation about mocking a mailing service. I tried few methods but some were confusing and some were really complex. Then I found Mock-JavaMail dependency which is quite easy to handle. Just add it and we are done.

I am using SBT project therefore using SBT dependency but you can find other relevant dependency on maven repository that will suit your project.

Let’s take an example:

First we add the required dependencies in our project.

Then we create the necessary variables in our class.

Here I am taking email and password from system environment variables, to use them you need to set them as following:

export email=your_email@domain.com

export password=your_password

Then we will use above variable in method mentioned below. I’ve written two methods, one for sending mail to multiple emails and one for a single email id and I’ve used method overloading functionality for that.

Now let’s move to the real motive of this blog which is mocking mail.  I’ve used ScalaTest for testing my class. Now all you have to do is to write unit test cases and Mock-JavaMail will redirect all mails to in-memory .

Note: Mock-JavaMail will redirect all mails to in-memory so don’t forget to add scope as test otherwise you will not be able to send mail from your production code.

“groupId” % “artifactId” % “version” % “scope”

Unit Test Code:

See complete source code on GitHub

Written by 

Prabhat is a Sr. Software Consultant with more than 2 years of experience in C, C++, Java, MySQL, and Scala. His interests are in Cyber Security, Web Development, and New technologies. Prabhat developed software and website on different platforms which include VB6, VB.NET, ASP.NET, PHP, Wordpress, OpenCart, SMF, VBulletin, HTML5, MyBB. Prabhat is focused and result oriented, self-motivated and team-oriented and effective team player.

1 thought on “Mocking Mail API in Scala

Leave a Reply

%d bloggers like this: