【问题标题】:Grails Spock Unit Test - What is "1 *" and why "too few invocations"?Grails Spock 单元测试 - 什么是“1 *”以及为什么“调用太少”?
【发布时间】:2015-03-04 21:25:29
【问题描述】:

我在单元测试中看到我从其他人那里继承的控制器的以下代码:

  when: "When the controller executes a registration"
      controller.index()

    then: "the signup should show registration again"
      1 * controller.cService.getRegions() >> [] 
      1 * controller.dService.chkAvail(_) >> "AVAILABLE"
      1 * controller.uService.createUser(_) >> { a-> throw new RuntimeException("Roll me back!")}
      1 * controller.pService.registerPayMethod(_) >> { cc-> true }
      view == "/signUp/su"

我了解 spock 单元测试的基础知识,但我不了解这些 1 * 行。

我也遇到了多个错误,例如:

junit.framework.AssertionFailedError: Too few invocations for:

1 * controller.cService.getRegions() >> []   (0 invocations)

Unmatched invocations (ordered by similarity):

None

【问题讨论】:

  • 错误说,该方法没有被调用,而您希望它调用一次
  • @cfrick 谢谢,当开发人员没有阅读基础知识时会发生这种情况。因此,通过这种方式,我们可以验证特定方法是否被调用了一定次数。如果你想写你的评论作为答案。

标签: unit-testing grails spock


【解决方案1】:

你是在告诉 Spock,所讨论的方法必须被调用一次(1 * controller.cService.getRegions() >> [] 意味着,这个服务的getRegions 必须被调用一次(1 *)并且将返回一个空列表(@987654324 @))。但事实并非如此。这就是错误消息告诉您的内容 (0 invocations)。

【讨论】:

    【解决方案2】:

    请查看以下示例:-

    def "List Invocation Calls Test"() {
        given:
        List list = Mock();
        when:
    
        list.add(5)
        list.add(15)
        list.add(25)
    
        then:
        3 * list.add(_)
    }
    

    【讨论】:

    • 你能解释一下你的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 2014-06-21
    • 2016-06-17
    相关资源
    最近更新 更多