Monday, June 17, 2013

[Grails] How to test controllers that use i18n messages.

Issue description:

1) If the controller action I want to test calls "message()" or "g.message()" then I all of my integration tests that use that line of code will error with, "No bean named 'messageSource' is defined".
2) If the controller action I want to test calls "message()" or "g.message()" then I will get the following error message.

message() is applicable for argument types: (java.util.LinkedHashMap) values

Solution Or Walk Around:

Write a ControllerUnitTestCase extension to support tests controllers that use i18n messages, then let all your unit test cases of controllers extends it.

class ExtendedControllerUnitTestCase extends ControllerUnitTestCase {
def props

protected void setUp() {

props = new Properties()
def stream = new FileInputStream("grails-app/i18n/")
props.load stream


def mockI18N = { controller ->
controller.metaClass.message = { Map map ->
if (!map.code)
return ""
if (map.args) {
def formatter = new MessageFormat("")
formatter.applyPattern props.getProperty(map.code)
return formatter.format(map.args.toArray())
} else {
return props.getProperty(map.code)

More info about this solution can be found: 

No comments:

Post a Comment