Match Objects or Methods

Although matchers1 are normally used to specify acceptable parameter values2, they can also be used to specify acceptable objects or methods in an expectation, using an API syntax similar to that of jMock 1. To do so, use a matcher where you would normally refer to a mock object directly in the invocation count clause3. Then chain clauses together to define the expected invocation. The following clauses are supported:

method(m) A method matching the Matcher m is expected.
method(r) A method with a name that matches the regular expression r is expected.
with(m1m2, ... mn) The parameters must match matchers m1 to mn.
withNoArguments() There must be no parameters

An expectation of this form can be followed by ordering constraints (sequences4 and states5) and actions (e.g. returning values6 or throwing exceptions7) like a normal, literal expectation.

Examples

To allow invocations of any bean property getter on any mock object:

allowing (any(Object.class)).method("get.*").withNoArguments();

Allow a method to be called once on any one of a collection of mock objects:

oneOf (anyOf(same(o1),same(o2),same(o3))).method("doSomething");

Links:

1. matchers: http://www.jmock.org/matchers.html

2. specify acceptable parameter values: http://www.jmock.org/parameters.html

3. invocation count clause: http://www.jmock.org/cardinality.html

4. sequences: http://www.jmock.org/sequences.html

5. states: http://www.jmock.org/states.html

6. returning values: http://www.jmock.org/returning.html

7. throwing exceptions: http://www.jmock.org/throwing.html