geofflane/grails-constraints — Issue #16: Potential support for @TestFor 
Author: samcday
Created: 2012-01-29 01:39:13+00:00
State: open

Hi Geoff,

Pull request #15 offers support for @TestMixin annotations in Grails 2 unit tests for Constraints.

There is another feature that can expand this even more, and that's supporting the @TestFor annotation outright. This would mean instead of this:

@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
}
}

You can do this:

@TestFor(MyConstraint)
class MyConstraintTests {
void testStuff() {
// No need to setup constraint, it's automatically setup in each test.

// 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
}
}

@TestFor handles weaving in the relevant mixin class, so in the latter example ConstraintUnitTestMixin would still get mixed into the class at compile time. TestFor has the added avantage of automatically calling testFor† to setup the class under test in each test method. Sicne this is now the standard in Grails for testing core artefacts like Services/Controllers/Taglibs, it is nice to offer this for custom artefacts like Constraints too.

The caveat is to offer this support a small amount of monkey-patching is required. A hook needs to be added to _Events.groovy to let TestForTransformation know about your custom artefact. Take a look at [how I did it in my of my plugins](https://github.com/samcday/grails-binders/blob/master/scripts/_Events.groovy) and you'll see what I'm talking about.

I [posted](http://grails.1312388.n4.nabble.com/Grails-2-Test-mixins-for-custom-Artefacts-tt4335529.html) about this on the Grails user mailing list and Graeme Rocher responded without any complaints about this approach. He recommended a feature request be raised to have an official API for this in a future version of Grails 2.

So it's up to you really, if you want to add in the small amount of monkey-patching code to _Events.groovy then you can have @TestFor support now, or you can wait until there's an official mechanism to register custom artefacts.

Let me know what you think!

† well actually, TestForTransformation automatically calls mock\, testFor is just a convention and in the ConstraintUnitTestMixin it just calls mockConstraint