5

我有 TagLib、Service 和 TestCase 如下

如何在 taglib 中模拟服务以从服务中获得预期结果

标签库:

   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

1 回答 1

5

您需要使用 grailsmockFor来模拟服务。

查看模拟合作者

未经测试的例子:

def strictControl = mockFor(BaseService)
strictControl.demand.findAttributeValue(1..1) { arg1 -> return true }
taglib.baseService = strictControl.createMock()
于 2012-10-07T10:53:02.753 回答