【问题标题】:Spock mock method implementation not working when checking invocations number检查调用编号时Spock模拟方法实现不起作用
【发布时间】:2020-03-05 10:04:14
【问题描述】:

我在使用 Spock 模拟方法时遇到问题。下面是我正在使用的代码。无需任何更改,一切正常 - 模拟实现正常工作并返回“模拟”字符串。但是,如果我使用调用检查 (3 * notifier.test()) 取消注释行,我的方法 notify 的模拟实现不会调用并且测试失败,因为通知器模拟返回 null。为什么会这样?

class Aaaaa extends Specification {
    class Notifier {
        def test() {
            println("Called in impl...")
            return "impl"
        }
    }

    def "Should verify notify was called"() {
        given:
        Notifier notifier = Mock(Notifier)
        notifier.test() >> {
            println("Called in mock...")
            return "mock"
        }

        when:
        notifier.test()
        notifier.test()
        def result = notifier.test()

        then:
//        3 * notifier.test()
        result == "mock"
    }
}

【问题讨论】:

    标签: java unit-testing groovy mocking spock


    【解决方案1】:

    Mockito 风格的 stubbing 和 mocking 分成两个独立的 语句将不起作用

    来自文档: http://spockframework.org/spock/docs/1.0/interaction_based_testing.html#_combining_mocking_and_stubbing

    需要在定义mock方法的同一行定义调用次数

    【讨论】:

      【解决方案2】:

      为关注的人发布实际答案:

          def "Should verify notify was called"() {
              given:
              Notifier notifier = Mock(Notifier)
      
              when:
              notifier.test()
              notifier.test()
              def result = notifier.test()
      
              then:
              3 * notifier.test() >> {
                  println("Called in mock...")
                  return "mock"
              }
              result == "mock"
          }
      

      【讨论】:

        猜你喜欢
        • 2016-08-20
        • 1970-01-01
        • 2019-08-29
        • 1970-01-01
        • 2016-03-04
        • 1970-01-01
        • 2016-12-11
        • 2013-12-29
        • 1970-01-01
        相关资源
        最近更新 更多