How to unit test a Grails After filter that updates the Model

190 Views Asked by At

How do I test a Grails filter which updates the model?

How do I inspect the model updated by a filter within a unit test?

I'm using Grails 2.3.4

Using the Grails Unit Testing guide

I have created a filter test:

@TestMixin(GrailsUnitTestMixin)
@TestFor(MyController)
@Mock(MyFilters)
class MyFiltersTest {
  @Test
  void myFilterAddsAModelEntry(){
     def model
     withFilters(action:"index"){
       model=controller.index()
     }

     println "model in test: $model"

     assert model.filterObject == "hello world"
  } 
}

However, the test fails as the returned model does not include the filterObject, even though the filters are called.

With the following Controller:

class MyController {
  def index(){
    println "MyController.index() called"
    // return empty model
    [:]
}

and Filter:

class MyFilters {
  def filters = {
    all(controller:'*', action:'*') {
      before = {
        println "before filter called"
      }
      after {Map model ->
        println "after filter called"
        model.filterObject="hello world"
        println "filtered model: $model"
        model
      }
      afterView = { Exception e -> }
    }
  }
}

The test generates the following output:

before filter called...
MyController.index() called...
after filter called
filtered model: [filterObject:hello world]
model in test: [:]
0

There are 0 best solutions below