|
by Tyler Jennings, with Dave Hoover
May 5, 2006
|
Dave Hoover : Home
|
public void testInterceptArgument() {
List arguments = new ArrayList();
Mock mockSubmissionTracker = mock(SubmissionTracker.class);
mockSubmissionTracker.expects(once()).method("record").will(captureArgumentsIn(arguments));
SecretLottery lotto = new SecretLottery( (SubmissionTracker)
mockSubmissionTracker.proxy());
lotto.createTicket();
LotteryTicket ticket = (LotteryTicket) arguments.get(0);
assertEquals("Secret Number", 12345, ticket.number);
}
private Stub captureArgumentsIn(List argumentList) {
return new ArgumentInterceptor(argumentList);
}
class ArgumentInterceptor implements Stub {
List arguments;
public ArgumentInterceptor(List argumentList) {
arguments = argumentList;
}
public Object invoke(Invocation invocation) throws Throwable {
arguments.addAll(invocation.parameterValues);
return null;
}
public StringBuffer describeTo(StringBuffer buffer) {
return buffer;
}
}
public void testInterceptArgument() {
Mock mockSubmissionTracker = mock(SubmissionTracker.class);
mockSubmissionTracker.expects(once()).method("record").with(ticketNumber(12345));
SecretLottery lotto = new SecretLottery( (SubmissionTracker) mockSubmissionTracker.proxy());
lotto.createTicket();
}
private Constraint ticketNumber(final int ticketNumber) {
return new Constraint() {
public boolean eval(Object arg) {
LotteryTicket ticket = (LotteryTicket) arg;
return ticketNumber == ticket.number;
}
public StringBuffer describeTo(StringBuffer buffer) {
return buffer.append(ticketNumber);
}
}
}
While this example works fairly well, each new test method would likely require its own Constraint. When the verification in the eval method becomes complex, it can become difficult to determine why a test is failing. An Argument Interceptor allows for traditional jUnit assertions, providing clearer failures for complex verfications.
Home : Dave Hoover
| Copyright © 2001-2006 Red Squirrel Design, Inc. All Rights Reserved. |