dimanche 1 avril 2018

Groovy Singleton and testing issue (with Spock)

There's a discusson here about testing and singletons... but that is about Java patterns.

My question is specifically about the Groovy @Singleton (annotation) way of implementing this pattern.

This seems like another bit of Groovy Goodness. But I have a bit of a problem when testing (with Spock) using a class which has this annotation.

If any of the state of this instance changes during a test (from the pristine, just-constructed state), as far as my experiments indicate this will then carry through to the next test... I tested MySingletonClass.instance's hashCode() with several tests and they all came back the same. Perhaps this isn't surprising.

But ... wouldn't it be better if Spock could (using the kind of uber-Groovy magic I can only speculate on) somehow reset the class between tests? I.e. by creating a new instance?

There is an obvious workaround: to incorporate a reset method into each @Singleton class where its state might change during a test. And then call that reset method in setup() ... in fact I use a common Specification subclass, CommonProjectSpec, from which all my real Specifications subclass... so that would be simple enough to implement.

But it seems a bit inelegant. Is there any other option? Should I maybe submit this as a Spock suggested enhancement?

Aucun commentaire:

Enregistrer un commentaire