简体   繁体   English

忽略Mockito中的方法调用

[英]Ignoring method calls in Mockito

With Mockito, is it possible to ignore a method call to a mock? 使用Mockito,是否可以忽略对模拟的方法调用?

Eg for the mock rugger created with mock(MyRugger.class) : 例如,对于模拟rugger与创建mock(MyRugger.class)

class Pepe {

  public void runner() {     
    rugger.doIt(); 
    rugger.flushIt();
    rugger.boilIt();     
  } 
}

I need only test runner() but avoid the method flushIt() . 我只需要测试runner()但要避免方法flushIt()

To reset a mock in Mockito, simply call reset on it. 要在Mockito中重置模拟,只需在其上调用reset Note the very real concern mentioned in the above link and the JavaDoc for reset stating that it may represent bad design. 请注意上面链接中提到的非常实际的问题, 有关resetJavaDoc指出它可能表示不良的设计。

This should generally be avoided, but there are times when you simply need to do this. 通常应该避免这种情况,但是有时您只是需要这样做。 The below is an example on how to use it, not a good example of when to use it. 以下是有关如何使用它的示例, 而不是何时使用它的好示例。

Object value = mock(Object.class);

when(value.equals(null)).thenReturn(true);
assertTrue(value.equals(null));
verify(value).equals(null);

reset(value);

assertFalse(value.equals(null));
verify(value).equals(null);

Mockito is nice and will not verify calls unless you ask it to. Mockito很不错,除非您要求,否则不会验证电话。 So if you don't want to verify flush() just verify the methods you care about: 因此,如果您不想验证flush()只需验证您关心的方法:

verify(rugger).doIt();
verify(rugger).boilIt();

If you want to verify that flush() was NOT called, use: 如果要验证未调用flush() ,请使用:

verify(rugger, never()).flush();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM