我正在嘗試爲調用服務方法的控制器編寫測試。我想嘲笑該服務中的依賴方法。如何在Grails集成測試中部分模擬服務
我的規格如下:
MyController myController = new MyController()
def mockMyService
def "My spy should be called"() {
when:
mockMyService = Spy(MyService) {
methodToSpy() >> {
println "methodToSpy called"
} // stub out content of this fn
}
myController.myService = mockMyService
myController.callService()
then:
1 * mockMyService.methodToSpy()
}
當我嘗試運行這個測試,我得到以下錯誤:
Failure: | My spy should be called(spybug.MyControllerSpec) | Too few invocations for: 1 * mockMyService.methodToSpy() (0 invocations) Unmatched invocations (ordered by similarity): 1 * mockMyService.serviceMethod() 1 * mockMyService.invokeMethod('methodToSpy', []) 1 * mockMyService.invokeMethod('println', ['in serviceMethod about to call methodToSpy']) 1 * mockMyService.invokeMethod('println', ['Back from methodToSpy'])
正如你所看到的,斯波克被捕獲的Groovy invokeMethod中調用,而不是隨後調用實際方法。這是爲什麼發生?
完整的項目可用here。
您正在編寫單元或集成測試嗎? –