So, we all want to make our code covered good with tests all over, and when coding in grails, this is easier than ever, using all the cool mixins, like TestFor and Mock .. However I’ve stumbled upon a pretty weird problem in Grails 2.5.1 and probably also other versions of grails. I’ve made some Spock Unit tests that test a controllers full functionality including calling services where Domain objects are saved. Using the simple mixing from grails @TestFor(Controller.class) and @Mock([DomainClass1, DomainClass2]) . This works fine most of the time. BUT sometimes I get this Exception from Grails:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to groovy.lang.Closure
 at org.codehaus.groovy.grails.validation.DefaultConstraintEvaluator.evaluateConstraints(
 at org.codehaus.groovy.grails.validation.DefaultConstraintEvaluator.evaluateConstraints(
 at org.codehaus.groovy.grails.validation.DefaultConstraintEvaluator.evaluate(
 at org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass.initializeConstraints(
 at org.codehaus.groovy.grails.commons.DefaultGrailsDomainClass.getConstrainedProperties(
 at org.codehaus.groovy.grails.validation.GrailsDomainClassValidator.validate(
 at org.grails.datastore.gorm.GormValidationApi.doValidate(GormValidationApi.groovy:64)
 at org.grails.datastore.gorm.GormValidationApi.validate(GormValidationApi.groovy:145)
 at asa.HoldControllerSpec.setup(HoldControllerSpec.groovy:73)

So what is this ?? My domain class looks just like any other domain classes, with a couple of fields and then some constraints. I debugged my way down in the grails code, and found that for some reason, it cannot cast the static constraints closure to a closure when it is PRIVATE ( default when not giving any modifiers ), but if I make it public everything is sweet and working perfect as expected.

So if you ever get this error, just make your constraints public and there you go, everything works as expected. I can’t see any reason why it works sometimes and sometimes not, but the solution is at least there.

just change your constraints form

static constraint = {
     field nullable: false, min:0


public static constraint = {
     field nullable: false, min:0