rag*_*ghu 5 grails unit-testing taglib grails-2.0
我有如下的 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()
}
}
Run Code Online (Sandbox Code Playgroud)
服务:
class BaseService {
def findAttributeValue(arg1) {
return false
}
}
Run Code Online (Sandbox Code Playgroud)
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"
}
}
Run Code Online (Sandbox Code Playgroud)
但它得到错误条件不满足。获取输出 = " "
预期输出 = "输出"
您需要使用 grailsmockFor来模拟服务。
查看模拟合作者
未经测试的示例:
def strictControl = mockFor(BaseService)
strictControl.demand.findAttributeValue(1..1) { arg1 -> return true }
taglib.baseService = strictControl.createMock()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2595 次 |
| 最近记录: |