gpt4 book ai didi

unit-testing - 如何在 grails TagLib 单元测试中模拟服务

转载 作者:行者123 更新时间:2023-12-04 19:13:27 25 4
gpt4 key购买 nike

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

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

预期输出 = "输出"

最佳答案

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

Mocking Collaborators

未经测试的示例:

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

关于unit-testing - 如何在 grails TagLib 单元测试中模拟服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12757855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com