Friday, October 21, 2011

Grails dynamic finders not working in Unit Tests

I ran into a problem with my unit test in Grails.

One of the dynamic finders was not working. What was strange was that it worked fine when I ran the app normally. It only failed in the unitTests.

groovy.lang.MissingMethodException: No signature of method: static com.domain.myDomain.findByCode() is applicable for argument types: (java.lang.String) values: [myCode]
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(
at groovy.lang.MetaClassImpl.invokeStaticMethod(
at groovy.lang.ExpandoMetaClass.invokeStaticMethod(


When unit testing, grails mocks out all backend access. In order to do this it must dynamically update the domain classes (e.g. save method), so that they dont try to talk to the DB.

Therefore when using any unit testing on domain object you must first mock it out. This is easily done in the unitTest class in the setUp() method

mockDomain myDomain

It can save you a lot of hassle

No comments: