给定一个带有参数的方法在 Java 中,例如
public class Foo {
public Bar theBar(Bar bar) { /*... */ }
}
当 stub /模拟 foo 时,我如何告诉它接受任何参数并返回它? (时髦)
def fooStub = Stub(Foo) {
theBar(/*what to pass here*/) >> { x -> x }
}
如您所见,我传递了身份函数。但是我不知道该传递什么作为参数。 _
不起作用,因为它是一个 ArrayList
,因此不是 Bar
最佳答案
您可以通过以下方式 stub 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
}
}
关于java - Spock:在 stub 中返回输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46607848/