2013-05-20 153 views
0

我在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

如果这比创建新实例和填充依赖关系更快,则可以使用服务的模拟实现。

有时您可以拥有复杂的服务,这取决于其他服务,并且设置所有必需结构的努力很高,那么您可以使用Grails mockFor()方法,只是模拟您将使用的特定方法。

Grails docs告诉你如何模拟将在你的单元测试中使用的类。

在你的例子中,我没有看到优势,因为Something只是foo的持有者。

1

您可以使用自SomethingdefineBeans(参见Testing Spring Beans),而setUpgiven已被宣布为beanresources.groovy

defineBeans{ 
    mySomething(Something){bean -> 
     //To take care of the transitive dependencies inside Something 
     bean.autowire = true 
    } 
} 
+0

+1。 'defineBeans'是另一种方式,但在Grails 2.2.2之前,如果使用'grailsApplication.mainContext.getBean()',你的模拟bean没有在主要上下文中注册。 –

+0

我记得你的[建议改进](http://jira.grails.org/browse/GRAILS-9980)我的朋友。感谢您提出这个问题。 :) – dmahapatro

+0

一旦将它分配给'controller'成员,我几乎不会从'mainContext'获取bean。因为在这种情况下,它在'src/groovy'我假定没有交易涉及,但是是的改善是有帮助的。 – dmahapatro

相关问题