geofflane/grails-constraints — pull request #15 by samcday (2012-01-28 23:45:00+00:00)
Title: @TestMixin support for constraint unit testing

Hi Geoff,

Another patch for you. This one focuses on making unit testing constraints more pleasant in Grails 2.

A new class has been created, ConstraintUnitTestMixin. This class extends from GrailsUnitTestMixin, this follows the convention of the built-in unit test mixins for [Controllers](https://github.com/grails/grails-core/blob/master/grails-plugin-testing/src/main/groovy/grails/test/mixin/web/ControllerUnitTestMixin.groovy)/[Services](https://github.com/grails/grails-core/blob/master/grails-plugin-testing/src/main/groovy/grails/test/mixin/services/ServiceUnitTestMixin.groovy)/etc.

Using this class is simple, here's an example:

@TestMixin(ConstraintUnitTestMixin)
class MyConstraintTests {
void testStuff() {
def constraint = testFor(MyConstraint)

// Params are automatically mixed in to the test class and exposed
// to the constraint with the call above.
params.foo = "bar"

assert constraint.validate("foo", null, null) == true
}
}

Note that the meta-class is being modified on every call to testFor(), this is deliberate, as GrailsUnitTestMixin listens for changes to meta-classes and rolls them back between tests. Nifty huh?

Let me know what you think!