Spock invocation for Groovy's generated getters using a final field
Asked Answered
S

1

7

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...

Subvene answered 20/12, 2013 at 10:55 Comment(0)
F
12

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.

Focus answered 20/12, 2013 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.