Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 313
Francois Bourgeois Avatar asked Dec 20 '13 10:12

Francois Bourgeois


People also ask

Does Spock support method arguments in Groovy?

contains a timestamp. Spock supports examining method arguments using Groovy closures. Groovy closures are very similar to Java 8 lambda expressions, so you don’t need any special knowledge to understand them if you have already worked with Java 8.

Where do I put Groovy tests in Spock?

This file is called CustomerReaderSpec.groovy, and it should be placed in the folder src/test/groovy under the same Java package as the class under test. We have instructed Spock to run unit tests that end in *Spec in the Maven pom file, as described in the previous section.

How to get the arguments of a mock method in Spock?

In Spock we can also get a hold on the arguments that are passed to a method call of a mock and we can write assertions to check the parameters for certain conditions. When we create a mock in Spock and invoke a method on the mock the arguments are matched using the equals () implementation of the argument type.

Does Groovy have getters and setters?

] In fact, like before with the Groovy defined Loan, Groovy will invoke the getter or setter for that property defined in the Java class. Clearly, the ability to seemingly access properties cuts down on the amount of code one must write; plus, the perceived safety and encapsulation that these methods provide is still present.


1 Answers

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.

like image 186
Peter Niederwieser Avatar answered Oct 18 '22 18:10

Peter Niederwieser