Mockito to the Rescue

After all the abuse in my previous post, I feel a bit guilty. Luckily Mockito provides a way out of that problem by allowing hamcrest matchers being used to verify arguments. Here we go:

 verify(listener).propertyChange(
                (PropertyChangeEvent)argThat(
                        new HasEqualState(
                                new PropertyChangeEvent(holder, "value", "Old", "New"))));

It is not nice, but it works. Of course I also had to implement the HasEqualState matcher along these lines:

  public boolean matches(Object actual) {
            if (actual == null)
                return false;
            if (actual.getClass() != reference.getClass()) // this might be naïve
                return false;
 
            Class clazz = reference.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
 
                Object refValue = field.get(reference);
                Object actValue = field.get(actual);
 
                if (refValue != actValue) {
                    if (refValue == null || !refValue.equals(actValue)) {
                        return false;
                    }
                }
            }       
        return true;
    }

Posted

in

by

Tags:

Comments

One response to “Mockito to the Rescue”

  1. szczepiq Avatar
    szczepiq

    Mockito 1.8.0 has a nice feature for verifying arguments more naturally: http://mockito.googlecode.com/svn/branches/1.8.0/javadoc/org/mockito/ArgumentCaptor.html

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.