【问题标题】:Grails 2.0.0 mock service always returns true?Grails 2.0.0 模拟服务总是返回 true?
【发布时间】:2014-05-16 02:20:18
【问题描述】:

我试图模拟我的控制器中有一个服务,但它总是返回 true。服务如下所示:

def someService (x, y){...}

然后我在控制器测试中模拟了它: mockservice.demand.someService () {-> return false }

它一直返回 true。我不知道怎么了。我尝试包含参数,但它仍然没有返回错误。这个怎么做?

PS:请原谅错别字,我现在正在打电话。谢谢

【问题讨论】:

  • 模拟时参数必须匹配。

标签: grails grails-2.0


【解决方案1】:

我假设您在控制器中使用此服务,并且单元测试来自控制器。我还假设您在文档中阅读了mocking collaborators

@TestFor(MyController)
class MyControllerSpec {
  def setup() {
    def mockServiceControl = mockFor(SomeService)
    //here you limit the amount of times that the method should be called.
    mockServiceControl.demand.someService(0..1) { x, y ->
      return false
    }
    //probably you're missing to assign the attribute in the controller
    controller.someService = mockServiceControl.createMock()
  }

  void testSomething() {
    controller.action()

    //assert response

    //Then verify that the demand mocking is correct
    mockServiceControl.verify()
  }
}

【讨论】:

  • mockFor() 给出了一个 mockControl。你必须调用createMock() 来获取模拟对象。
  • 是的,感谢缺少的部分。我感觉很懒 :-)
猜你喜欢
  • 1970-01-01
  • 2015-07-20
  • 2023-03-14
  • 2013-08-06
  • 2017-05-10
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多