Grails Integration Test - Form Submission Is Always InvalidToken

I tried in my Unit Test to test duplicate forms, as in the docs, and it worked. http://grails.imtqy.com/grails-doc/3.0.x/guide/testing.html#unitTestingControllers

But in my integration test, it was always unsuccessful and flagged as invalidToken. I write it the same way as Unit Test in the tokenHolder part.

So how to handle a valid withForm token in an 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' } } 

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] } } 
+5
source share
1 answer

In integration tests, the parameters must be set for the new controller instance, which must be created manually (see http://grails.imtqy.com/grails-doc/2.5.0/guide/testing.html#integrationTesting ). Also, the session is not available in the default integration tests. You can get it through RequestContextHolder as follows: RequestContextHolder.currentRequestAttributes().session .

The full 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: Grails 3.0 recommends using functional tests instead of integration tests. See โ€œControllersโ€ in the Integration Testing section of the Grails reference documentation.

+1
source

All Articles