Testing mock arguments with Mockito

Mockito uses equals() to compare arguments by default, as in:

verify(myMock).handle("an argument));

This works well when comparing Strings, Integer…etc, but breaks down when the argument is an instance of a class which does not override the Object’s equals() method, such as a Throwable:

//the class to mock
class ExceptionHandler{
   void handle(Throwable t){
     ...
   }
}

public class MyApp {

   private final ExceptionHandler exceptionHandler ;

   MyApp (final ExceptionHandler exceptionHandler){
      this.exceptionHandler = exceptionHandler;
   }

   public void runLogic(int param){
         exceptionHandler.handle(new Throwable(String.format("param is %d", param)));
}
}

Two possible solutions in that case:

First method – using an argument captor

 ExceptionHandler mockExceptionHandler = mock(ExceptionHandler.class);
 ArgumentCaptor<Throwable> captor = ArgumentCaptor.forClass(Throwable.class);
 new MyApp(mockExceptionHandler).runLogic(12);
 verify(mockExceptionHandler).handle(captor.capture());
 Throwable throwable = captor.getValue();
 assertThat(throwable.getMessage(),is("param is 12"));

Second method- using a custom matcher

class ThrowableMatcher extends ArgumentMatcher<Throwable> {
   private String message;

   ThrowableMatcher (String message){
      this.message = message;
   }

   @Override
   public boolean matches(Object o) {
     return ((Throwable)o).getMessage().equals(message);
   }
}

...
 ExceptionHandler mockExceptionHandler = mock(ExceptionHandler.class);
 new MyApp(mockExceptionHandler).runLogic(12);
 verify(mockExceptionHandler).handle(argThat(new ThrowableMatcher("param is 12")));

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s