Sunday, January 9, 2011

Testing sending emails with Grails

If you'll ever find yourself in need to test some mail sending piece of code in Grails be advised that there are 2 ways of doing it (both options work only in integration tests!)

The grails-mail way

Once you have your piece of code in place what you can do is to set the
setting in Config.groovy and skip sending emials entirely. You can then use the return value from mailService.sendMail call to inspect what would have been sent to the server.

The "all-the-way-through" way

If you'd like to see if everything really goes through to the mail server you can always use Dumpster. It's a very elegant library giving you basically 3 things:

  • A SimpleSmtpServer.start() method

  • The SimpleSmtpServer instance as a result of the method call above

  • SimpleSmtpServer.stop()
So what you can do is to start the server at the beginning of your test, send the mail simply to localhost:25 (assuming you don't have sendmail listening on the same port of course) and shut it down after you're done with it.

To sort of enable Dumpster in your tests either add the dumbster-1.6.jar to your lib folder or add the following dependency to BuildConfig.groovy
dependencies {
test 'dumbster:dumbster:1.6'
Make sure you enable repoCentral()!

Here's how easy it is to use Dumpster to test sending emails in a grails integration test:
import org.junit.Test
import com.dumbster.smtp.SimpleSmtpServer

class ExampleIntegrationTests {

def mailService

@Test void willReceiveEmail() {
def server = SimpleSmtpServer.start()

mailService.sendMail {
to ""
from ""
body "This is the body"


assert server.receivedEmail.toList().size() == 1

// a little dump to see what's in the email :)
server.receivedEmail.each { println it }
Check out the Dumpster examples for more. I like it!

Final warning

A word of caution related to the grails-mail plugin: in version 1.0-SNAPSHOT you need to manually add a repository for the required dependencies to be properly resolved. In general I recommend using version 0.9 because it works out-of-the-box. To do that either specify the version while installing the plugin like this:
grails install-plugin mail 0.9
or if you've already installed it in the default version you can always edit the file and change the plugin version there.

No comments: