2012-09-28 106 views
4

有沒有一種方法來測試這個攔截器?在我的測試中它被忽略了。在集成測試中在Grails中測試BeforeInterceptor

代碼:

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) 
    } 

} 

回答

3

根據這一線索http://grails.1312388.n4.nabble.com/Controller-interceptors-and-unit-tests-td1326852.html格雷姆表示你必須單獨調用攔截。在我們的例子,因爲我們使用的是攔截檢查令牌,它的每一個動作一樣,我們使用:

@Before 
void setUp() 
{ 
    super.setUp(); 
    controller.params.token = "8bf062eb-ec4e-44ae-8872-23fad8eca2ce" 
    if (!controller.beforeInterceptor()) 
    { 
     fail("beforeInterceptor failed"); 
    }  
} 

我想,如果每個單元測試指定攔截不同的參數,你就必須每次單獨調用它。如果不想這個,我認爲你必須使用像聖盃的功能測試,這將通過在整個生命週期:http://grails.org/plugin/functional-test

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') 
} 

那些例子是用於攔截後測試,但攔截之前同樣應該適用於也。