我正在使用Grails 2.4.4在Spock单元测试中渲染GSP。GSP有许多自定义标记库,其中许多称为外部服务。问题是我无法将存根的服务注入这些taglib中,而当我调用该服务时,它始终为null。这是我试图获得最简单的案例的方法:
@TestMixin(GroovyPageUnitTestMixin)
@Mock(FooTagLib)
class MyGspSpec extends Specification {
def setup() {
def barStub = Stub(BarService)
def tagLibStub = GroovyStub(FooTagLib, global:true) {
}
tagLibStub.barService = barStub
}
def 'test method'() {
when: String result = render('myView', model:[:])
then: assert result != null
}
}
标签库:
class FooTagLib {
static String namespace = "baz"
BarService barService
Closure<StreamCharBuffer> foo = { GroovyPageAttibutess attrs ->
out << barService.something()
}
}
_foo.gsp的内容:
<baz:foo/>
我也尝试过这个:
FooTagLib.metaClass.barService = Stub(BarService) //also tried GroovyStub
我什至尝试将吸气剂放在taglib上并存根,但它也不起作用:
在设置中:
def barService = Stub(BarService)
GroovyStub(FooTagLib, global:true) {
getBarService() >> barService
}
在taglib中:
BarService barService
BarService getBarService() { return barService }
//....
out << getBarService().something()
最后,唯一有效的方法(与吸气剂一起使用)是:
FooTagLib.metaClass.getBarService = { -> return Stub(BarService) }
但这似乎是一个非常糟糕的hack。
我不确定如何将其存根版本注入taglib。在我看来,至少其中一种应该有效,但是显然我在做错事。
这就是我通过tagLib的单位规格的方式:
@TestFor(FooTagLib)
class FooTagLibSpec extends Specification {
def setup() {
// tagLib is available by default of above annotation is used
tagLib.barService = Mock(BarService) {
// Mock the service and stub the response
1 * serviceMethod() >> { "Hello World Returns" }
}
}
void "test something"() {
expect: 'applying template would result in mocked response'
applyTemplate('<baz:foo/>') == "Hello World Returns"
}
void "test taglib method call"() {
expect:
tagLib.foo() == "Hello World Returns"
}
}
class FooTagLib {
static defaultEncodeAs = [taglib:'html']
static String namespace = "baz"
BarService barService
Closure<StreamCharBuffer> foo = { attrs ->
out << barService.serviceMethod()
}
}
class BarService {
def serviceMethod() { "Hello World" }
}
我希望我能够满足您在测试中寻找的检查点。您还可以看到spec能够BarService
无问题地进行模拟。如果需要信息,请大喊大叫。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句