2012-12-19 51 views
2

我有一個Grails 2.1應用程序,其具有控制器,該控制器上的服務調用的方法,傳入的請求和響應:使用具有GMock一個模擬服務測試一個Grails控制器(0.8.0)

class FooController { 
    def myService 
    def anAction() { 
     response.setContentType('text/xml') 
     myservice.service(request,response) 
} 

我想單元測試這個方法。我想這樣做使用GMock(0.8.0版本),所以這是我的嘗試:

def testAnAction() { 
    controller.myService = mock() { 
     service(request,response).returns(true) 
    } 
    play { 
     assertTrue controller.anAction() 
    } 
} 

現在這個失敗說,它失敗的請求的期望。

Missing property expectation for 'request' on 'Mock for MyService' 

但是,如果我寫我的測試是這樣的:

def testAnAction() { 
    def mockService = mock() 
    mockService.service(request,response).returns(true) 
    controller.myService = mockService 
    play { 
     assertTrue controller.anAction() 
    } 
} 

測試將通過罰款。據我所知,它們都是GMock語法的有效用法,那麼爲什麼第一個失敗,第二個失敗呢?

乾杯,

回答

3

我假設你寫你的測試在Grails生成一個測試類FooControllerTest

以這種方式,FooControllerTest類被註解@TestFor(FooController)這要注入一些有用的屬性

所以request是你的測試類,而不是一個在局部範圍內可變屬性

這就是爲什麼它不能從內部閉包到達。

我相信,下面的代碼可以工作(我還沒有測試過):

def testAnAction() { 
    def currentRequest = request 
    def currentResponse = response 
    controller.myService = mock() { 
     service(currentRequest,currentResponse).returns(true) 
    } 
    play { 
     assertTrue controller.anAction() 
    } 
} 
相關問題