0

我有一堂课src/groovy

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 有什么好处,我应该在这里使用它们吗?

4

2 回答 2

1

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

有时您可能有一个复杂的服务,它依赖于其他服务,并且设置所有必需的结构的工作量很大,那么您可以使用 Grails mockFor()方法并模拟您将使用的特定方法。

Grails 文档向您展示了如何模拟将在您的单元测试中使用的类。

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

于 2013-05-20T21:55:00.867 回答
1

您可以在声明为内部时或之后使用defineBeans(请参阅测试 Spring BeanssetUpgivenSomethingbeanresources.groovy

defineBeans{
   mySomething(Something){bean ->
      //To take care of the transitive dependencies inside Something
      bean.autowire = true 
   }
}
于 2013-05-20T22:15:16.970 回答