jeudi 14 septembre 2017

A template for testing @Validatable classes in Grails

Here is a simple template for testing validateable classes in Grails. Using unroll it makes possible the systematic testing of validation rules.

For more complex validation rules, the require the call to services or involve the setup of multiple attributes of the command object, you might want to add more complex tests.

package my.package

import grails.test.mixin.TestMixin
import grails.test.mixin.web.ControllerUnitTestMixin
import spock.lang.Specification
import spock.lang.Unroll

/** * Created by hschoonjans on 14/09/2017. */
@TestMixin(ControllerUnitTestMixin)
class @artifact.name@ extends Specification {

    @Unroll
    def "It fails to validate a bad value '#value' for the '#field' field"() {
        setup:
        def command = newInstance([(field): value])

        expect:
        !command.validate([field])

        where:
        field       | value
        "someField" | "wrongValue"    }

    @Unroll
    def "It validates a good value '#value' for the '#field' field"() {
        setup:
        def command = newInstance([(field): value])

        expect:
        command.validate([field])

        where:
        field       | value
        "someField" | "goodValue"    }

    private @artifact.name@ newInstance(Map params) {
        new @artifact.name@(params)
    }
}

Aucun commentaire:

Enregistrer un commentaire