Pages

Thursday, January 22, 2009

Using assertions within your mockito ArgumentMatcher implementations

I've been using mockito in my Java work recently and have really enjoyed its functionality and ease of use.  Lately I've been trying to do a better job of verifying my SUT's indirect outputs, both behavior and state.  Behavior is easy to verify with mocking frameworks and mockito is no different.  State verification of indirect outputs is bit trickier, but still pretty easy to do once you know what matcher combination you need to use.  For mockito, you use the org.mockito.ArgumentMatcher<T> class and its subclasses (all implement the org.hamcrest.Matcher interface).  There is a single abstract method that you should implement, the matches(Object argument) method.  This method returns a boolean result. 

Today, I was having a conversation with a co-worker of mine, Ryan Anderson, about the use of the ArgumentMatcher.  Ryan wondered if one could use JUnit assertions within the matches method implementation and just return true if all of the assertions passed; failed assertions will not reach the return statement.  Indeed, you can use assertions in the ArgumentMatcher implementation.  JUnit assertions actually throw an instance of java.lang.AssertionError, thus your stack trace will show exactly which assertion within the ArgumentMatcher failed.  Much better using the assertions than testing and returning a boolean value.  Might be helpful for your testing efforts.

3 comments:

  1. Maybe I misread, but doesn't the JavaDoc explicitly say not to use an assertion within the Matcher. I mean... if it works - great! I just wonder why it was called out specifically.

    ReplyDelete
  2. I didn't pick up on that. Thanks for the heads up. Unfortunately, the documentation doesn't state why you shouldn't use assertions. Returning false doesn't give you any information about what exactly did not match. I wonder if it has something to do with allowing the verify() to do the assertion and throw the verification exception.

    ReplyDelete
  3. I've posted a comment on the mockito list to further delve into the issue of why assertions should not be used within your custom ArgumentMatcher implementations. You can follow the conversation at http://groups.google.com/group/mockito/browse_thread/thread/ce196f0460aa27cb.

    ReplyDelete