jeudi 4 juin 2015

Grails 2.4.4 controller test on save() return empty model

I have a test for a PersonController, it just executes save() with no params, so an invalid person is created. It should return the invalid person in the model and show the create view. But the model is empty.

The test:

import org.junit.*
import grails.test.mixin.*

@TestFor(PersonController)
@Mock(Person)
class PersonControllerTests {
   ...
   void testSave() {
       controller.save() // creates invalid person, redirects to create
       assert model.personInstance != null
       assert view == '/person/create'

       response.reset()

       populateValidParams(params)
       controller.save()

       assert response.redirectedUrl == '/person/show/1'
       assert controller.flash.message != null
       assert Person.count() == 1
   }
   ...
}

The controller:

class PersonController {

   ...
    def save() {
        def personInstance = new Person(params)
        if (!personInstance.save(flush: true)) {
            render(view: "create", model: [personInstance: personInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'person.label', default: 'Person'), personInstance.id])
        redirect(action: "show", id: personInstance.id)
    }
   ...
}

The output:

junit.framework.AssertionFailedError: Assertion failed: 

assert model.personInstance != null
       |     |              |
       [:]   null           false

    at demographic.PersonControllerTests.testSave(PersonControllerTests.groovy:43)

How can I get the right model?

Is this the expected behavior or is this a Grails bug?

Aucun commentaire:

Enregistrer un commentaire