Spock:存根中的返回输入参数
问题描述:
给定一个参数为的Java(例如,Spock:存根中的返回输入参数
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
}
}
+0
您是否尝试过使用'Foo'和'Bar'作为Java类? – user3001
+0
@ user3001是的,当'Foo'和'Bar'是Java类时,它的工作原理完全相同,只是测试了这个例子并得到了相同的结果。 –
你有'@ CompileStatic'或'@ TypeChecked'你的规范呢?你可以发布你的整个代码,没有理由不应该使用'_'。 –