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

Bor*_*vić 21 java junit assert verify mockito

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

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());
}
Run Code Online (Sandbox Code Playgroud)

Mockito.verify如果模型中的Observable.setChanged()方法没有调用方法,则抛出异常.

问题:没有添加loggers/System.print.out我无法意识到当前测试失败的方法是什么.有没有办法与jUnit Assert方法类似:

Assert.assertEquals(
  String.format("instances %s, %s should be equal", inst1, inst2),
  inst1.getParam(), 
  inst2.getParam()
);
Run Code Online (Sandbox Code Playgroud)

解:

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());
Run Code Online (Sandbox Code Playgroud)

Arm*_*min 19

这样做(简单明了):

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

  • 将原因作为第二个参数传递通常比连接消息更好.`throw new MockitoAssertionError("message",e)` (6认同)
  • MockitoAssertionError没有带有参数MockitoAssertionError(String,Exception)的构造函数,我改用`new AssertionError(“ message”,exception)`,因为这是JUnit为断言抛出的异常类型。 (2认同)

Joe*_*der 13

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

verify(mock, description("This will print on failure")).someMethod("some arg");
Run Code Online (Sandbox Code Playgroud)

  • 以这种方式使用“org.mockito.Mockito.description”意味着“times(1)”;您正在验证是否使用给定的参数 _exactly_ 调用该方法一次。但您还可以做更多的事情。如果你想验证它被调用了 10 次: `verify(mock, ti​​mes(10).description("This will print if the method isn't Called 10 times")).someMethod("some arg");`或 `verify(mock, never().description("如果曾经调用过 someMethod")).someMethod("some arg");` 或 `verify(mock, atLeastOnce().description("这将打印如果 someMethod 从未使用任何参数调用")).someMethod(anyString());` (7认同)

Ube*_*rto 6

你不能在mockito做.Mockito语法很容易测试预期的行为,但它没有测试状态的概念.

你要做的是在模拟失败期望时获得一些不在模拟对象中的信息.

如果您真的想这样做,我会看到两种常用方法:要么创建自己的验证模式,要么实现接口

org.mockito.verification;
public static interface VerificationMode
Run Code Online (Sandbox Code Playgroud)

并添加一个类似于atLeastOnceMsd(String msg)的方法,该方法将在失败时显示消息,或者将模型中当前测试的方法添加到视图对象

例如,内环中有类似的线.

  view.setName("now we are testing " + method.getName());
Run Code Online (Sandbox Code Playgroud)