【问题标题】:Argument capturing on the insides of closures in SpockSpock 闭包内部的参数捕获
【发布时间】:2017-12-06 15:45:21
【问题描述】:

我正在尝试测试一个使用闭包进行调用的方法,如下所示:

def foo(Long param) {
    AnObject.doSomething {
       bar(param)
    }
}

我想测试 doSomething 是通过一个闭包调用的,该闭包调用 bar 并在其中包含预期值。

我能够通过创建一个间谍并执行正确测试 doSomething 调用

when:
    service.foo(1L)
then:
    1 * AnObject.doSomething{_}

但是,我似乎找不到对闭包内容执行断言的方法。

用 1L 调用闭包 bar 的正确方法是什么?

【问题讨论】:

    标签: unit-testing groovy spock


    【解决方案1】:

    如果没有看到更多代码,我认为您需要监视提供 bar 方法的类。这有点做作,因为测试提供了闭包,但我认为它是这样的:

    import spock.lang.Specification
    
    class Bar {
        void bar(def param) {
            println param
        }
    }
    
    class DoSomethingTestSpec extends Specification {
    
        class AnObject {
    
            void doSomething(Closure c) {
    
                def param = 1L
    
                c.call(param)
            }
        }
    
        def "test AnObject doSomething calls the closure"() {
    
            given:
            def closure = { def p ->
                Bar.bar(p)
            }
    
            and:
            GroovySpy(Bar, global:true)
    
            and:
            AnObject anObject = new AnObject()
    
            when:
            anObject.doSomething(closure)
    
            then:
            1 * Bar.bar(_) >> { args ->
                assert args[0] == 1L
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多