Question

Following is my beforeInterceptor

def beforeInterceptor = {
    log.debug "============${actionName}=========="       
    if (!(actionName in ['search'])) {
        redirect controller: 'error', action: 'denied'
        return false
    }
}

I have no idea how to write test of beforeInterceptor. I have googled for it but no luck. I have tried to write its test cases on my own but not able to get actionName in the beforeInterceptor.

when:
    controller.beforeInterceptor()

or

when:
    controller.beforeInterceptor.call()
    controller.history(ticket)

Each time I got null in actionName.

Someone any idea: how to write test cases of beforeInterceptor (integration or unit)?

Was it helpful?

Solution

I created unit test for this, we can set action name in request there. And I called beforeInterceptor directly like:

@TestFor(PersonController)
@Mock([Person])
class PersonControllerSpec extends Specification {

  def setup() {
  }

  def cleanup() {
  }

  void "test beforeInterceptor"() {
    when:
    webRequest.actionName = "index"
    controller.beforeInterceptor()

    then:
    controller.response.redirectedUrl == '/error/denied'

    when:
    controller.response.reset()
    webRequest.actionName = "search"
    controller.beforeInterceptor()

    then:
    controller.response.redirectedUrl != '/error/denied'
  }
}

OTHER TIPS

Grails does not invoke interceptors or servlet filters when calling actions during integration testing. You should test interceptors and filters in isolation, using functional testing if necessary.

It will be easier to use and test with a filter instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top