Groovy Mocks
Mock objects areused to assist (typically unit) testing of classes in isolation.
The Groovy Mock resides in the groovy.mock.interceptor package. It is an all-groovy mock testing library.
In principle, it is used like this:
Groovy Mocks were inspired by EasyMock.
Find background information about Mocks and endo-testing under XP2000 conference paper.
For an extended example, see Using Testing Frameworks with Groovy
Features
- typical mock style of failing early
- mocks instance and class methods
- mocks final methods and final Collaborators
- mocks Groovy and Java Collaborators (but Caller must be groovy)
- can mock all objects of a given class (or a single Groovy object)
- mocks even if Collaborator cannot be injected into the Caller
- mocks even if Collaborator is not accessible on the Caller (no getter)
- demanded calls specified via recording calls on the Demand object (EasyMock style).
- cardinality specified as Ranges, default is
1..1; 'optional' can be achieved with0..1 - behavior specified via Closures, allowing static or calculated return values, throwing exceptions, asserting argument values, etc. (even tricky sequence constraints by sharing state in the testMethod scope between the behavior Closures)
- matching parameter list specified via Closure's parameter list, supporting typed or untyped params, default params, and varargs.
- not dependent on any external mock library
For an extensive list of usages see the unit tests that show how to use the mock package.
MockFor Tests
Some tests to demonstrate how to use the MockFor class.
StubFor Tests
Some tests to demonstrate how to use the StubFor class.
4 Comments
Hide/Show CommentsNov 03, 2008
Josh Brown
Since this page is titled "Using MockFor and StubFor", it would be nice to have an example of using StubFor.
Nov 03, 2008
Paul King
Yes, you are right. I will try to put something in over the next little while. Feel free to jump in before me and add something yourself if you feel up to it. The wiki is user editable. We'll review anything you add, so don't be afraid of getting it slightly wrong - we can tweak it if need be.
Jun 05, 2009
Christian Heise
Hmm, I don't get this on to work. Where is class Caller defined?
Jun 05, 2009
Paul King
Re: Hmm, I don't get this on to work. Where is class Caller defined?
It's just a code fragment. You can define Caller and Collaborator yourself, just make sure Caller has collaborateOne() and collaborateTwo() methods and Collaborator has one() and two() methods and link them up in the obvious way.