other register

Thursday, November 11, 2010

Integration Testing Mail function with Greenmail and Spock in Grails

Just managed to do spock integration test on my mail function running on grails.

I am using grails: 1.3.5, mail:  0.9,  spock: 0.4-groovy-1.7, greenmail: 1.2.1

RegistrationService will save the person's registration record to the database and then send a confirmation email to the person.
class RegistrationService {
def registrate (def person) { true)
// when using mail plugin, mailService is automatically injected so we don't have to declare it.
// also valid: mailService.sendMail
sendMail {
multipart true
subject "Hello World"
to person.emailAddress
from ""
body (view: '/email/confirm', model: [person: person])
return person

To make greenmail integration work, make sure the following settings in the Config.groovy test environment. Please make sure there is no real mail server setting there, and also no real mail server settings in the conf/spring/resources.xml, otherwise a real email will be sent. Bear in mind, by using greenmail plugin for integration test, there is no real mail sent.

Previously I was doing refactoring on someone else's code and got stuck on receiving real email and fail the integration test. Thanks to Mike Hugo on nabble to pinpoint this. Here comes the settings in Config.groovy test environment:

test {
  grails.mail.port = com.icegreen.greenmail.util.ServerSetupTest.SMTP.port = "localhost"
The spock integration test is as below:

import grails.plugin.spock.*;
import com.icegreen.greenmail.util.*

class RegistrationServiceIntegrationSpec extends IntegrationSpec{
def greenMail

def "create registration and send email"() {
def service = new RegistrationService()

when: "a user makes a valid registration" 
def person = new Person(title: 'Mr', lastName: 'joe',
firstName: 'blog', 'dateOfBirth': new Date(),
emailAddress: ''
assert person.validate(), true
person == service.registrate(person)

then: "the registration should be successful and the confirmation email should be sent successfully"
assert 1 == greenMail.getReceivedMessages().length

def message = greenMail.getReceivedMessages()[0]
assert "" == GreenMailUtil.getAddressList(message.from)
assert "Hello World" == message.subject

No comments: