繁体   English   中英

Spock:在Stubs中返回输入参数

[英]Spock: Return input parameter in Stubs

给出一个带有Java参数的方法,例如

public class Foo {
   public Bar theBar(Bar bar) { /*... */ }   
}

当存根/模拟foo时,如何告诉它接受任何参数并返回它? Groovy

def fooStub = Stub(Foo) {
  theBar(/*what to pass here*/) >> { x -> x }
}

如你所见,我通过了身份功能。 但是我不知道要传递什么作为参数。 _不起作用,因为它是一个ArrayList ,因此不是Bar类型

您可以通过以下方式存根Foo类:

Foo foo = Stub(Foo)
foo.theBar(_ as Bar) >> { Bar bar -> bar }

这里有完整的例子:

import groovy.transform.Immutable
import spock.lang.Specification

class StubbingSpec extends Specification {

    def "stub that returns passed parameter"() {
        given:
        Foo foo = Stub(Foo)
        foo.theBar(_ as Bar) >> { Bar bar -> bar }

        when:
        def result = foo.theBar(new Bar(10))

        then:
        result.id == 10
    }

    static class Foo {
        Bar theBar(Bar bar) {
            return null
        }
    }

    @Immutable
    static class Bar {
        Integer id
    }
}

我不确定你是什么意思。 _是正确的事情。 为什么你认为它是一个ArrayList 它是Object类型,可以用于任何事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM