[英]Spock invocation for Groovy's generated getters using a final field
Groovy generates getters and setters for all your class' fields. Groovy为您所有类的字段生成getter和setter 。 So when you do this:
所以当你这样做时:
class Foo {
final bar
}
new Foo().bar
you're actually calling the generated method Foo.getBar()
. 你实际上正在调用生成的方法
Foo.getBar()
。
I have a Spock specification that likes to check the invocations of such a generated getter: 我有一个Spock规范,喜欢检查这样生成的getter的调用:
def "some spock test"() {
given: def fooMock = Mock(Foo)
when: someFunction(fooMock)
then: 1 * fooMock.getBar()
}
someFunction()
does fooMock.bar
but I always get someFunction()
做fooMock.bar
但我总是得到
Too few invocations for:
1 * fooMock.getBar() (0 invocations)
1 * fooMock.bar
doesn't work, either. 1 * fooMock.bar
也不起作用。 How can I check that bar
is read from Foo
in the test? 如何在测试中检查从
Foo
读取的bar
? It works, if I omit final
, but this is a crappy solution... 它有效,如果我省略
final
,但这是一个糟糕的解决方案......
For a final
property, Groovy generates a final
getter method. 对于
final
属性,Groovy生成final
getter方法。 However, test doubles created with Mock()
, Stub()
, or Spy()
are purely proxy-based, and therefore cannot intercept final methods. 但是,使用
Mock()
, Stub()
或Spy()
创建的测试双Mock()
纯粹是基于代理的,因此无法拦截最终方法。
Since your code under test is written in Groovy, you can use a GroovyMock()
instead, which solves the problem. 由于您的测试代码是用Groovy编写的,因此您可以使用
GroovyMock()
来解决问题。
PS: Both 1 * foo.getBar()
and 1 * foo.bar
are valid notations. PS:
1 * foo.getBar()
和1 * foo.bar
都是有效的符号。
PPS: Only prefer GroovyMock()
over Mock()
if you have a concrete reason (mocking a final method, mocking a dynamic method, etc.). PPS:如果你有一个具体的原因(
Mock()
最终方法, Mock()
动态方法等),只喜欢GroovyMock()
不是Mock()
)。 For details, see the reference documentation . 有关详细信息,请参阅参考文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.