If you are wondering how to mock the localizaton provider in a Grails Controller, these are two example on how to do it.
The first one (FooController) is used when you want to have an instance of MessageSource injected as a member of your controller.
class FooController {
def messageSource
def index = {
def someMessage = messageSource.getMessage("some.key")
log.debug("Localized message: " + someMessage)
render(someMessage)
}
}
And its test class:
class FooControllerTests extends ControllerUnitTestCase {
void testIndex() {
//controller.messageSource = [getMessage: { def key, def locale -> return key }]
controller.messageSource = [getMessage: { def key -> return key }] //returns the input key
controller.index()
assertEquals "Should return a localized key", "some.key", controller.response.contentAsString
}
}
The second one (BarController) is when you prefer to use the “message” closure:
class BarController {
def index = {
def someMessage = message(code: "some.key", default: "Some default message")
log.debug("Localized message: " + someMessage)
render(someMessage)
}
}
Finally, how to mock it:
class FooControllerTests extends ControllerUnitTestCase {
void testIndex() {
//controller.messageSource = [getMessage: { def key, def locale -> return key }]
controller.messageSource = [getMessage: { def key -> return key }] //returns the input key
controller.index()
assertEquals "Should return a localized key", "some.key", controller.response.contentAsString
}
}
Quick and simple. I hope you enjoy these simple and useful examples.
Recent Comments