Groovy generates getters and setters for all your class' fields. So when you do this:
class Foo {
final bar
}
new Foo().bar
you're actually calling the generated method Foo.getBar()
.
I have a Spock specification that likes to check the invocations of such a generated 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
Too few invocations for:
1 * fooMock.getBar() (0 invocations)
1 * fooMock.bar
doesn't work, either. How can I check that bar
is read from Foo
in the test? It works, if I omit final
, but this is a crappy solution...
For a final
property, Groovy generates a final
getter method. However, test doubles created with Mock()
, Stub()
, or Spy()
are purely proxy-based, and therefore cannot intercept final methods.
Since your code under test is written in Groovy, you can use a GroovyMock()
instead, which solves the problem.
PS: Both 1 * foo.getBar()
and 1 * foo.bar
are valid notations.
PPS: Only prefer GroovyMock()
over Mock()
if you have a concrete reason (mocking a final method, mocking a dynamic method, etc.). For details, see the reference documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.