mercredi 26 août 2015

mocking formula-derived fields in Grails 2.2.1

I have a Domain class that uses a constraint with formula to calculate several fields. The fields are nullable, but when I am unit testing, the created objects fail to save, throwing ValidationException.

When I test this same code in while running the debugger (not in unit test), the fields are null, yet there are no errors.

I feel that if I could Mock the formula to return 0, I could run the test successfully. For example: Part.metaClass.getNumberOfObj1 = { return 0 }. Of course, this does not work.

Is there a way to mock the mapping of a formula onto these fields so the object can be persisted? Or, if not, is there a way to modify my setup to eliminate the (weird) errors that I am getting?

The Domain Class

class Part extends Base {
    ...
    Long    numberOfObj1
    Long    numberOfObj2
    Long    numberOfObj3

    static hasMany = [obj1:Obj1,obj2:Obj2,obj3:Obj3]

    static mapping = {
        numberOfObj1  formula: '(select count(id) from ' + Base.defaultSchema() + '.obj_1 ob1 where (ob1.pt_id = ID and ob1.deleted = \'F\'))'
        numberOfObj2  formula: '(select count(id) from ' + Base.defaultSchema() + '.obj_2 ob2 where (ob2.pt_id = ID)'
        numberOfObj3  formula: '(select count(id) from ' + Base.defaultSchema() + '.obj_3 ob1 where (ob3.pt_id = ID )'  
    ... }  
}

The Unit test

@TestMixin(ControllerUnitTestMixin)
@TestFor(PartController)
class PartControllerSpec extends BaseTestSpec {
    def "given a part search, when the create action is called"() {
        given:
            def obj1= createObj1()
            params.number = "1"
            params.rev = "A"

        when:
            controller.create()

        then:
            //test stuff
    }
}

Inside controller.create()

def create() {
    newPart = new Part(number:params.number,
                       revision:params.rev)//fields are null here
    try{
        newPart.save(flush:true, failOnError:true)
    } catch (Throwable th) {
        return
    }

The Error

grails.validation.ValidationException: Validation error occured during call to save():
- Field error in object 'com.Part' on field 'numberOfObj1': rejected value [null];codes [com.Part.numberOfObj1.nullable.error.com.Part.numberOfObj1,...

Aucun commentaire:

Enregistrer un commentaire