Tuesday, June 15, 2004

A little EasyMock trick

I had a problem with EasyMock ... I had to validate a call into a method that passed an exception. Exceptions don't compare well to each other so this was causing problems.

Fortunately, EasyMock has an escape clause for this purpose, you can override how it compares expected vs. actual arguments for a particular method. Thus:

public class ExceptionAwareArgumentsMatcher extends AbstractMatcher
{
  protected boolean argumentMatches(Object expected, Object actual)
  {
    if (expected instanceof Throwable)
      return expected.getClass().equals(actual.getClass());

    return super.argumentMatches(expected, actual);
  }
}

This just checks that the exception passed into the mock object is the right type, not that it is any particular instance.

In use, it looks like this:

MockControl c = MockControl.createStrictControl(ErrorHandler.class);
ErrorHandler eh = (ErrorHandler) c.getMock();

eh.error(LOG,
  "Unable to order cartoon character 'wilma' due to dependency cycle:"
  + " A cycle has been detected from the initial goal [wilma]",
  null,
  new CyclicGoalChainException(new Goal("")));

c.setMatcher(new ExceptionAwareArgumentsMatcher());

c.replay();

3 comments:

  1. Aha... Now I can do the same for arrays, a problem I had been having for a little while now. Nice...

    -Harish

    ReplyDelete
  2. Harish, Did you try it out for an array? Did it work fine for you? If yes can you please pass down the solution to me. Thanks!

    Richa

    ReplyDelete
  3. Harish, Did you try it out for an array? Did it work fine for you? If yes can you please pass down the solution to me. Thanks!

    Richa

    ReplyDelete

Please note that this is not a support forum for Tapestry. Requests for help will be deleted. Please subscribe to the Tapestry user mailing list if you are in need of support, or contact me directly for professional (for pay) support.

Spammers: Don't bother. I delete your comments and it's a waste of time for both of us. 垃圾邮件发送者:不要打扰。我删除您的评论和它的时间对我们双方的浪费