Skip to content

Instantly share code, notes, and snippets.

@nbkhope
Created January 20, 2017 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nbkhope/8327d0178ee132931ce955b207ba3e14 to your computer and use it in GitHub Desktop.
Save nbkhope/8327d0178ee132931ce955b207ba3e14 to your computer and use it in GitHub Desktop.
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
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