[英]Spock: Return input parameter in Stubs
Given an method with a parameter in Java , eg 给出一个带有Java参数的方法,例如
public class Foo {
public Bar theBar(Bar bar) { /*... */ }
}
When stubbing/ mocking foo, how do I tell it to accept any argument and return it? 当存根/模拟foo时,如何告诉它接受任何参数并返回它? ( Groovy ) ( Groovy )
def fooStub = Stub(Foo) {
theBar(/*what to pass here*/) >> { x -> x }
}
As you can see I passed the identity function. 如你所见,我通过了身份功能。 However I do not know what to pass as argument. 但是我不知道要传递什么作为参数。 _
does not work because it is an ArrayList
and thus not of type Bar
_
不起作用,因为它是一个ArrayList
,因此不是Bar
类型
You can stub Foo
class in following way: 您可以通过以下方式存根Foo
类:
Foo foo = Stub(Foo)
foo.theBar(_ as Bar) >> { Bar bar -> bar }
And here is full example: 这里有完整的例子:
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
}
}
I'm not sure what you mean. 我不确定你是什么意思。 _
is the right thing to pass. _
是正确的事情。 Why do you think it is an ArrayList
? 为什么你认为它是一个ArrayList
? It is of type Object
and can be used for anything. 它是Object
类型,可以用于任何事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.