有没有办法测试这个拦截器?在我的测试中它被忽略了。
代码:
class BaseDomainController {
def beforeInterceptor = {
throw new RuntimeException()
if(!isAdmin()){
redirect(controller: 'login', action: 'show')
return
}
}
}
class BaseDomainControllerSpec extends IntegrationSpec{
BaseDomainController controller = new BaseDomainController()
def 'some test'(){
given:
controller.index()
expect:
thrown(RuntimeException)
}
}
答案 0 :(得分:3)
根据这个帖子http://grails.1312388.n4.nabble.com/Controller-interceptors-and-unit-tests-td1326852.html Graeme表示你必须分别调用拦截器。在我们的例子中,由于我们使用拦截器来检查令牌,并且对于每个操作都是相同的,我们使用了:
@Before
void setUp()
{
super.setUp();
controller.params.token = "8bf062eb-ec4e-44ae-8872-23fad8eca2ce"
if (!controller.beforeInterceptor())
{
fail("beforeInterceptor failed");
}
}
我想如果每个单元测试为拦截器指定不同的参数,则每次都必须单独调用它。如果不想这样做,我认为你必须使用Grail的功能测试,它将贯穿整个生命周期:http://grails.org/plugin/functional-test
答案 1 :(得分:1)
Grails文档声明:
在集成测试期间调用操作时,Grails不会调用拦截器或servlet过滤器。您应该单独测试拦截器和过滤器,必要时使用功能测试。
这也适用于单元测试,您的控制器动作不受定义的拦截器的影响。
鉴于你有:
def afterInterceptor = [action: this.&interceptAfter, only: ['actionWithAfterInterceptor','someOther']]
private interceptAfter(model) { model.lastName = "Threepwood" }
要测试拦截器,你应该:
验证拦截是否适用于所需的操作
void "After interceptor applied to correct actions"() {
expect: 'Interceptor method is the correct one'
controller.afterInterceptor.action.method == "interceptAfter"
and: 'Interceptor is applied to correct action'
that controller.afterInterceptor.only, contains('actionWithAfterInterceptor','someOther')
}
验证拦截器方法是否具有所需的效果
void "Verify interceptor functionality"() {
when: 'After interceptor is applied to the model'
def model = [firstName: "Guybrush"]
controller.afterInterceptor.action.doCall(model)
then: 'Model is modified as expected'
model.firstName == "Guybrush"
model.lastName == "Threepwood"
}
或者,如果您没有拦截器,请确认没有任何
void "Verify there is no before interceptor"() {
expect: 'There is no before interceptor'
!controller.hasProperty('beforeInterceptor')
}
这些例子是用于拦截器之后的测试,但同样适用于拦截器之前。