我在src/groovy
测试Grails的控制器具有来自SRC豆/常规
class Something {
def foo
}
这是resources.groovy
beans = {
mySomething(Something)
}
在我的控制器类我用这个:
class MyController {
def mySomething
def index() {
mySomething.foo = "bar"
render mySomething.foo
}
}
我该如何测试?
@TestFor(MyController)
class MyControllerSpecification extends Specification {
def "test bean"
given:
controller.mySomething = new Something() //is this the best way?
when:
controller.index()
then
response.contentAsString == "bar"
}
问题
这是测试的最佳方式?我通常会看到为类创建的Mocks。 Mocks有什么好处,我应该在这里使用它们吗?
+1。 'defineBeans'是另一种方式,但在Grails 2.2.2之前,如果使用'grailsApplication.mainContext.getBean()',你的模拟bean没有在主要上下文中注册。 –
我记得你的[建议改进](http://jira.grails.org/browse/GRAILS-9980)我的朋友。感谢您提出这个问题。 :) – dmahapatro
一旦将它分配给'controller'成员,我几乎不会从'mainContext'获取bean。因为在这种情况下,它在'src/groovy'我假定没有交易涉及,但是是的改善是有帮助的。 – dmahapatro