Paramater ConstraintsTo avoid over specific tests, jMock lets the programmer specify constraints over the actual parameters to a call, rather than just test for equality against expected values. A constraint is an object that implements the Constraint interface. It must do two things:
The org.jmock.constraint package contains many constraint implementations and the programmer can easily specify their own constraints by writing their own implementation(s) of the Constraint interface. The 'C' ClassBecause expressions that instantiate arrays of constraints can become rather lengthy, static factory methods with terse names that create different constraint objects are implemented in the C class. For example, the following expression: new Constraint[] { new IsEqual(new Integer(0)), new IsEqual("hello, world"), new IsEqual(new Double(0.0)) }; Can be replaced by: C.args( C.eq(new Integer(0)), C.eq("hello, world"), C.eq(new Double(0.0)) ); Or even: C.eq( new Integer(0), "hello, world", new Double(0.0) ); Sugar MethodsBecause the most common constraint is that the parameter value must be equal to an expected value, the Mock class has sugar methods to add expectations and matches against expected values. For example: mock.expectVoid( "methodName", new Object[]{new Integer(0),"hello, world",new Double(0.0)} ); Methods with one argument do not need to create an object array, and are overloaded on all primitive types: mock.expectVoid( "oneArg", 0.0 ); Writing Custom ConstraintsAlthough not very common, it is occasionally necessary to write new constraints. One situation in which this is useful is to test the events fired by an object. Because the event source creates a new event object for each event it fires, a test cannot compare an expected event object for equality against an actual event object. Instead, the programmer can write a custom constraint that tests whether the fields of the event have the expected values.
To create a new constraint, write a class that implements the
Constraint
interface, implements the
import org.jmock.Constraint; class StartsWith implements Constraint { private String prefix; public StartsWith( String prefix ) { this.prefix = prefix; } public boolean eval( Object o ) { return o instanceof String && ((String)o).startsWith(prefix); } public String toString() { return "a string starting with \"" + prefix + "\""; } } |