我有TagLib,Service和TestCase如下
如何模拟taglib中的服务以从服务中获取预期结果
的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"
}
}
但它得到的错误条件不满意。获得输出=“”
预期输出=“输出”
答案 0 :(得分:4)
您需要使用grails mockFor
来模拟服务。
未经测试的例子:
def strictControl = mockFor(BaseService)
strictControl.demand.findAttributeValue(1..1) { arg1 -> return true }
taglib.baseService = strictControl.createMock()