Created
January 20, 2017 21:02
-
-
Save nbkhope/8327d0178ee132931ce955b207ba3e14 to your computer and use it in GitHub Desktop.
Grails 3 Unit Testing (Controller)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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' | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in Grails 3.3 the unit tests should implement ControllerUnitTest and not have TestFor