2012-10-06 109 views
4

我有標籤庫,服務和測試用例如下如何嘲笑Grails的標籤庫單元測試服務

如何在標籤庫嘲笑服務,從服務中獲得預期的結果

標籤庫:

class SampleTagLib { 

    static namespace = "sample" 
    def baseService 

    def writeName = { attrs, body -> 
     def result = baseService.findAttributeValue(attrs.something) 

     if(result) 
      out << body() 
    } 
} 

服務:

class BaseService { 

    def findAttributeValue(arg1) { 

     return false 
    } 
} 

TagLibUnitTestCase:

import spock.lang.* 
import grails.plugin.spock.* 
import org.junit.* 
import grails.test.mixin.* 
import grails.test.mixin.support.* 

import grails.test.mixin.Mock 

@TestFor(SampleTagLib) 
@Mock(BaseService) 
class SampleTagLibSpec extends Specification { 
     def template 

     def setup(){ 

     tagLib.baseService = Mock(BaseService) 
     } 


     def 'writeName'(){ 
     given: 
     tagLib.baseService.findAttributeValue(_) >> true 
     def template ='<sample:writeName something='value'>output</sample:writeName>' 


     when: 'we render the template' 
     def output = applyTemplate(template, [sonething:'value') 

     then: 'output' 
     output =="output" 
    } 
} 

但它得到錯誤條件不滿意。獲得輸出=「」

預計輸出=「輸出」

回答

4

您需要使用Grails mockFor模擬出該服務。

參見Mocking Collaborators

未測試實施例:

def strictControl = mockFor(BaseService) 
strictControl.demand.findAttributeValue(1..1) { arg1 -> return true } 
taglib.baseService = strictControl.createMock()