1

As an addendum to my other question: How to create Spock mocks outside of a specification class? - is it possible to change the behaviour of Mocks outside a specification?

In our project we have a lot of code in our Specifications that reads like this:

someService.findById(SomeMother.SOME_OBJECT.id) >> SomeMother.SOME_OBJECT
someService.findById(_) >> {throw new IllegalArgumentException("No such object")}

I would rather have code like

Helper.register(SomeMother.SOME_OBJECT).to(someService)

so i don't have to duplicate the mocking logic everywhere and. However it seems that I cannot change the behaviour of Mocks outside of a specification as the Mock simply registers the call instead of recognising that I want to change it's behaviour. Is there a way to do this or do I have to repeat all my initialisation logic over and over and over again?

Community
  • 1
  • 1
Jan Thomä
  • 13,296
  • 6
  • 55
  • 83

1 Answers1

0

Today, the only way to share mocking related code between classes is via a base class. Once Spock supports Groovy 2.3 mixins, mixins will likely be the way to go.

If you find yourself sharing mocks a lot, consider using fake objects instead. Typically, mocks are very specific to the test at hand.

Peter Niederwieser
  • 121,412
  • 21
  • 324
  • 259