Skip to content

Unit test: Controller classes

pschneider-manzell edited this page Dec 9, 2012 · 1 revision

Unit testing controllers

The controller under test in the following examples was created by using the grails generate-controller command for the domain class Author

You can find all unit tests for the AuthorController here: AuthorControllerSpec

Testing redirect

def 'index action'() {
setup:
mockLogging(AuthorController, true)

when:
controller.index()

then:
redirectArgs.action == "list"
}

Testing paging

def 'list action: 2 authors and max = 1'() {
setup:
mockLogging(AuthorController, true)
mockDomain(Author, [fistAuthorInstance, secondAuthorInstance])
controller.params.max = 1

expect:
controller.list() == [authorInstanceList: [fistAuthorInstance], authorInstanceTotal: 2]

where:
fistAuthorInstance = new Author(firstname: "John1", lastname: "Doe1")
secondAuthorInstance = new Author(firstname: "John2", lastname: "Doe2")
}

Testing page with params copied to the model

setup:
mockLogging(AuthorController, true)
mockDomain(Author)
controller.params.firstname = firstname
controller.params.lastname = lastname

when:
def model = controller.create()

then:
model.authorInstance != null
model.authorInstance.firstname == firstname
model.authorInstance.lastname == lastname

where:
firstname = "John"
lastname = "Doe"
}

Testing save action with a valid domain object

def 'save action: valid author'() {
setup:
mockLogging(AuthorController, true)
mockDomain(Author)
mockI18N(AuthorController)
controller.params.firstname = "John"
controller.params.lastname = "Doe"

when:
controller.save()

then:
redirectArgs.action == "show"
controller.flash.message != null

}

Testing a save action with an invalid object

def 'save action: invalid author'() {
setup:
mockLogging(AuthorController, true)
mockDomain(Author)
mockForConstraintsTests(Author)
mockI18N(AuthorController)
controller.params.firstname = firstname
controller.params.lastname = lastname

when:
controller.save()

then:
renderArgs.view == "create"
renderArgs.model.authorInstance.firstname == firstname
renderArgs.model.authorInstance.lastname == lastname

where:
firstname = "John"
lastname = ""

}

Testing optimistic locking on update action

def 'update action: optimistic locking'() {
setup:
mockDomain(Author, [authorInstance])
mockLogging(AuthorController, true)
mockI18N(AuthorController)
controller.params.firstname = "John changed"
controller.params.lastname = "Doe changed"
//Decrease version of edited object to enforce optimistic locking validation
controller.params.version = (currentVersionInDB -1)
controller.params.id = authorInstance.id

when:
controller.update()

then:
renderArgs.view == "edit"
renderArgs.model.authorInstance == authorInstance
renderArgs.model.authorInstance.hasErrors()

where:
currentVersionInDB = 2
authorInstance = new Author(firstname: "John", lastname: "Doe", version: currentVersionInDB)
}