Recording and Replaying
How to make Mockolates do something (alternate syntax)
In stubbing and mocking the default expectation-based syntax was demonstrated, however Mockolate also supports a record-replay syntax for refactoring-friendly Mock Objects. To start using this syntax pass a Mockolate-created instance to record(instance)
, call any methods, getters and setters that are expected and then call replay(instance)
before passing the instance to whatever is going to use the it. Some expectations will use expect(...)
to set additional behaviour.
Using a nice Flavour,
var flavour:Flavour = nice(Flavour);
set it to record,
record(flavour);
we can stub a getter,
expect(flavour.name).returns("Butterscotch");
or a setter,
expect(flavour.name = true);
or a method with no arguments, and return a value,
expect(flavour.toString()).returns("Butterscotch");
stub a method with arguments, and return a reference,
var otherFlavour:Flavour = nice(Flavour);
var combinedFlavour:Flavour = nice(Flavour);
expect(flavour.combine(otherFlavour)).returns(combinedFlavour);
stub a method with arguments using Matchers from hamcrest-as3
expect(flavour.combine(expectArg(instanceOf(Flavour)))).returns(combinedFlavour);
stub a setter with arguments using Matchers,
expect(flavour.ingredients = expectArg(array("cookies", "cream")));
stub a method to dispatch an Event,
expect(flavour.combine(expectArg(anything)))
.returns(combinedFlavour)
.dispatches(new FlavourEvent(FlavourEvent.TASTE_EXPLOSION));
stub a method to call a Function,
expect(flavour.combine(expectArg(anything())))
.returns(combinedFlavour)
.calls(function():void {
trace("it's a mystery flavour");
});
stub a method to throw an Error,
expect(flavour.combine(expectArg(nullValue())))
.throws(new ArgumentError("Really, combine this flavour with <null>?"));
and finally before using the instance for real, call replay()
replay(flavour);
Customising behaviour
Additional behaviour not included in Mockolate can be added by implementing mockolate.ingredients.answers.Answer
. Examples of custom Answer
s are provided for handing HTTPService
result and fault calls. Decorating Mocolates has more details.