简体   繁体   English

如何在Grails TagLib单元测试中模拟服务

[英]How to mock a service in grails TagLib unit test

I have TagLib, Service and TestCase as follows 我有TagLib,Service和TestCase如下

How to mock a service in a taglib to get expected result from service 如何在taglib中模拟服务以从服务获得预期结果

TagLib: 标签库:

   class SampleTagLib {

     static namespace = "sample"
     def baseService

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

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

Service: 服务:

 class BaseService {

     def findAttributeValue(arg1) {

       return false  
     }
}

TagLibUnitTestCase: 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"
     }
 }

But it getting Error condition not satisfied. 但它得到的错误条件不满意。 Getting output = " " 获得输出=“”

Expected output = "output" 预期输出=“输出”

You need to use the grails mockFor to mock out the service. 您需要使用grails mockFor来模拟服务。

See Mocking Collaborators 请参阅模拟协作者

Untested Example: 未经测试的例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM