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:
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