geofflane / grails-constraints

Custom constraints plugin for Grails applications
Apache License 2.0
35 stars 11 forks source link

@TestMixin support for constraint unit testing #15

Closed samcday closed 12 years ago

samcday commented 12 years ago

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/Services/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!