Testing related JavaMail modules
Which you can't check without an IMAP server if your app is sending an email. But everything else can be done if you design your code correctly. What you need to do is separate your addiction. What does it mean?
In this case, your code only needs to access the third-party code (JavaMail) in one place (in most cases, only one class). Separate this class by interface from the rest of the code so you can use the mock object in your tests.
Here's an example you should NOT be doing (assuming JavaMail is an external dependency):
class Application {
public run(String[] receiverList, String message, String body) {
for (String receiver : receiverList) {
JavaMail.sendMessage(receiver, message, body);
}
}
}
You cannot check the for loop in this case. Do this instead:
class Application {
private IApplicatioNMail mail;
public Application(IApplicationMail mail) {
this.mail = mail;
}
public run(String[] receiverList, String message, String body) {
for (String receiver : receiverList) {
mail.sendMessage(receiver, message, body);
}
}
}
class JavaApplicationMail implement IApplicationMail {
public sendMessage(String receiver, String message, String body) {
JavaMail.sendMessage(receiver, message, body);
}
}
This way you can create a dummy (mock, whatever) in your tests to replace JavaApplicationMail. In your tests, the external receiver is never called).
The test might look something like this:
@Test
public void sentThreeMails() throws Exception {
IApplicationMail mailCounter = new MailCounter();
Application application = new Application(mailCounter);
application.run(new String[] { "one", "two", "three" }, "Hello", "Blah!");
assertEquals(3, mailCounter.calls);
}
class MailCounter implements IApplicationMail {
public counter = 0;
public sendMessage(String receiver, String message, String body) {
counter++;
}
}
source to share