【问题标题】:How to mock a service in grails TagLib unit test如何在 grails TagLib 单元测试中模拟服务
【发布时间】:2012-10-06 07:46:29
【问题描述】:

我有 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"
     }
 }

但它得到错误条件不满足。获取输出 = " "

预期输出 = “输出”

【问题讨论】:

    标签: unit-testing grails grails-2.0 taglib


    【解决方案1】:

    您需要使用 grails mockFor 来模拟服务。

    Mocking Collaborators

    未经测试的示例:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      相关资源
      最近更新 更多