有没有办法在Mockito的验证方法中使用类似jUnit Assert消息参数的东西?

2022-09-01 06:48:41

让我们假设一段测试代码:

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 将引发异常。Observable.setChanged()

问题:如果不添加,我无法意识到当前未通过测试的方法是什么。有没有办法拥有类似于方法的东西:loggers/System.print.outjUnit Assert

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

溶液:

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());

答案 1

这个问题很古老,但是Mockito v2.1.0 +现在有一个内置的功能。

verify(mock, description("This will print on failure")).someMethod("some arg");

下面@Lambart的评论中包含更多示例:

verify(mock, times(10).description("This will print if the method isn't called 10 times")).someMethod("some arg");
verify(mock, never().description("This will print if someMethod is ever called")).someMethod("some arg");
verify(mock, atLeastOnce().description("This will print if someMethod is never called with any argument")).someMethod(anyString());

答案 2

这确实是诀窍(简单明了):

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

推荐