Is there a way of having something like jUnit Assert message argument in Mockito's verify method?

Boris Pavlović picture Boris Pavlović · Nov 15, 2010 · Viewed 11.4k times · Source

Let's assume a snippet of testing code:

Observable model = Class.forName(fullyQualifiedMethodName).newInstance();
Observer view = Mockito.mock(Observer.class);
model.addObserver(view);
for (Method method : Class.forName(fullyQualifiedMethodName).getDeclaredMethods())
{
  method.invoke(model, composeParams(method));
  model.notifyObservers();
  Mockito.verify(
    view, Mockito.atLeastOnce()
  ).update(Mockito.<Observable>any(), Mockito.<Object>any());
}

Mockito.verify method throws an exception if a method in a model hasn't invoked Observable.setChanged() method.

Problem: without adding loggers/System.print.out I can't realize what's the current method that has failed the test. Is there a way of having something similar to jUnit Assert methods:

Assert.assertEquals(
  String.format("instances %s, %s should be equal", inst1, inst2),
  inst1.getParam(), 
  inst2.getParam()
);

SOLUTION:

verify(observer, new VerificationMode()
{
  @Override
  public void verify(VerificationData data)
  {
    assertTrue(
        format(
            "method %s doesn't call Observable#setChanged() after changing the state of the model",
            method.toString()
        ),
        data.getAllInvocations().size() > 0);
  }
}).update(Mockito.<Observable>any(), Mockito.<Object>any());

Answer

Armin picture Armin · Jul 2, 2012

This does the trick (simple and clear):

try {
 verify(myMockedObject, times(1)).doSomthing();
} catch (MockitoAssertionError error) {
    throw new MockitoAssertionError("Was expecting a call to myMockedObject.doSomthing but got ", error);
}