Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Grails 3 Unit Testing (Controller)
// Given the controller
class DemoController {
def hello() {
render "greetings!"
}
def greet() {
redirect action: 'hello'
}
}
// Write the following test:
package com.demo
import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(DemoController)
class DemoControllerSpec extends Specification {
void "test hello"() {
when:
controller.hello()
then:
response.text == 'greetings!'
}
void "test greet"() {
when:
controller.greet()
then:
response.redirectedUrl == '/demo/hello'
}
void "test something"() {
when:
// you can test params
params.sort = 'name'
params.max = 20
params.offset = 0
request.method = 'GET'
request.makeAjaxRequest()
controller.list()
then:
response.text == 'something'
response.xml.@title.text() == 'Great'
response.text == '{"book":"Great"}'
response.json.book == 'Great'
// see http://docs.grails.org/2.4.x/api/org/codehaus/groovy/grails/web/sitemesh/GrailsContentBufferingResponse.html
response.status == SC_METHOD_NOT_ALLOWED // or: SC_OK, SC_CREATED, SC_UNAUTHORIZED, SC_NOT_FOUND, etc.
response.redirectedUrl == '/some/where'
}
}
@ppazos

This comment has been minimized.

Copy link

ppazos commented Apr 24, 2019

in Grails 3.3 the unit tests should implement ControllerUnitTest and not have TestFor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.