Testing related JavaMail modules

Part of my application depends on JavaMail, message movement, etc. Can I test this module without having to start the IMAP server to run the tests? I always get stuck when it comes to testing stuff that depends on external servers or modules.

+2


source to share


3 answers


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++;
    }
}

      

+1


source


Try using mock for your test



+2


source


Running an IMAP server for your test suite might actually be a good idea. GreenMail was designed for this very purpose, it allows you to run IMAP / POP3 / SMTP servers in memory from Java code.

+1


source







All Articles