============= UPDATED ANSWER =================================
I am using grails 2.4.2 now.
Here you do not need to use Holders.applicationContext.getBean("messageSource") to receive a messageSource, it will be automatically entered.
So, an example Command object:
@Validateable class Test { def messageSource String aa static constraints = { aa blank:false, validator: {val, obj -> println obj.messageSource.getMessage("default.paginate.prev",null,LocaleContextHolder.locale) ... } ...
Test example:
void "test for valid data"() { when: def test = new Test(aa:'hello') def messageSource = Mock(MessageSource) test.messageSource = messageSource then: test.validate() }
Instead of Mock, you can also use mockFor.
========= OLD ANSWER =============
Instead of directly using messageSource in a Command object you can use service there and wrap messageSource with service .
Service example:
class I18nMessageService { MessageSource messageSource def getMessage(String code, Object[] args=null) { messageSource.getMessage(code,args,LocaleContextHolder.locale) } }
Command object example:
@Validateable class Test { def i18nMessageService String aa static constraints = { aa blank:false, validator: {val, obj -> println obj.i18nMessageService.getMessage("default.paginate.next") ... } } }
The i18nMessageService service is automatically injected into the Test command object during application startup.
For the i18nMessageService test, you must mock and enter manually.
Test example:
void "test for valid data"() { when: def test = new Test(aa:'hello') def i18nMessageServiceMock = mockFor(I18nMessageService) i18nMessageServiceMock.demand.getMessage {'message you wanted'} test.i18nMessageService = i18nMessageServiceMock.createMock() then: test.validate() }