Question

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

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top