Thursday, April 21, 2005

JMock Invocation Order

After many fruitless Google searches I finally found an example (on the JMock site no less) on how to ensure invocation order of methods:
"logger.expects(once()).method("setLoggingLevel").with(eq(Logger.WARNING))
.id("warning level set");
logger.expects(once()).method("warn").with(warningMessage)
.after("warning level set");
logger.stubs().method("getLoggingLevel").noParams()
.after("warning level set")
.will(returnValue(Logger.WARNING));

A rule of thumb to follow when specifying the expected order of method calls is: test the ordering of only those calls you want to occur in order. The example above allows the warn and getLoggingLevel methods to occur in any order, as long as they occur after the call to setLoggingLevel. Thus we can change the order in which our tested object calls warn and getLoggingLevel without breaking our tests."

So the ".id("warning level is set")" sets a property that the second and third calls check with ".after("warning level is set")".

EasyMock makes it easy by allowing you create a strict type of control object: "If you would like a "strict" Mock Object that checks the order of method calls, use MockControl.createStrictControl() to create its MockControl."

No comments: