I have tried in my Unit Test to test duplicate form submission like in the docs and it worked. http://grails.github.io/grails-doc/3.0.x/guide/testing.html#unitTestingControllers
But in my Integration Test, it was always failed and marked as invalidToken. I write it in the same way like unit test in tokenHolder's part.
So how to handle valid token withForm in Integration Test?
My Integration Test:
@TestFor(RegisterTestedController)
class RegisterTestedControllerIntSpec extends Specification {
void "test insert data register"() {
given:
controller.params.username == 'babaenciel'
controller.params.companyName == 'tamago'
when:
def tokenHolder = SynchronizerTokensHolder.store(session)
params[SynchronizerTokensHolder.TOKEN_URI] = '/registerTested/signUp'
params[SynchronizerTokensHolder.TOKEN_KEY] = tokenHolder.generateToken(params[SynchronizerTokensHolder.TOKEN_URI])
controller.signUp()
then:
controller.modelAndView.model.parameter.username == 'babaenciel'
controller.modelAndView.model.parameter.companyName == 'tamago'
}
}
The Controller:
class RegisterTestedController {
def signUp() {
log.info("session: " + session.properties)
log.info("request: " + request.properties)
log.info("params: " + params)
def invalidToken = false
withForm {
invalidToken = false
}.invalidToken {
invalidToken = true
}
log.info("invalid token: " + invalidToken)
if(invalidToken) {
flash.code = 'alert-red'
flash.message = message(code: "error.general.multipleSubmission")
redirect action:'index'
return
}
render view: 'index', model: [parameter: params]
}
}
In integration tests the params need to be set for a new controller instance that you have to create manually (See http://grails.github.io/grails-doc/2.5.0/guide/testing.html#integrationTesting). Also the session is not available in the integration tests by default. You can get it via the RequestContextHolder
like this: RequestContextHolder.currentRequestAttributes().session
.
The complete code should look like this:
YourController yourController = new YourController()
def token = SynchronizerTokensHolder.store(RequestContextHolder.currentRequestAttributes().session)
yourController.params[SynchronizerTokensHolder.TOKEN_URI] = '/yourController/yourAction'
yourController.params[SynchronizerTokensHolder.TOKEN_KEY] = token.generateToken(yourController.params[SynchronizerTokensHolder.TOKEN_URI])
yourController.yourAction()
Also note: In Grails 3.0 it is recommended to use functional tests instead of integration tests. See "Testing Controllers" in section Integration Testing of the Grails Reference Documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With