简体   繁体   English

验证使用 Mockito 调用方法的次数?

[英]Verifying the number of times the method was called using Mockito?

I am new to mockito... What I am trying to do is to use mockito and System.print out the number of times that a certain method was called...我是 mockito 的新手......我想要做的是使用 mockito 和 System.print 输出某个方法被调用的次数......

For example, The numer of times that the Class.doSomething() was called: n times例如 Class.doSomething() 被调用的次数:n 次

I guess we need to use verify() or Invocations but I have been searching up about this for hours but have not found any solutions...我想我们需要使用 verify() 或 Invocations 但我已经搜索了几个小时但没有找到任何解决方案......

Can someone please help me with this?有人可以帮我解决这个问题吗?

Thanks!谢谢!

I don't think you can print a message each time the method is called.我认为您不能在每次调用该方法时打印一条消息。 You can add the log on the production code or use proxy on the method for add logging layer.您可以在生产代码上添加日志或在添加日志层的方法上使用代理。

@Mock
private MockedObject mockedObject;


verify(mockedObject,times(2)).doSomething();
  1. assume that you have a class Sample With method doSomehting假设您有一个类 Sample With 方法 doSomehting
public class Sample {
    public void doSomething();
}
  1. in JUnit test case, verify the method was called n times using Mockito在 JUnit 测试用例中,使用 Mockito 验证该方法被调用了 n 次
@Test
public void testMockitoTimes {
    Sample sample = Mockito.mock(Sample.class);
    sample.doSomething(); ..... 
    Mockito.verfiy(sample, Mockito.times(n)).doSomething();
}
  1. there is a lot of link that you could refer, such as verify-a-method-is-called-two-times-with-mockito有很多链接可以参考,例如verify-a-method-is- called-two-times-with-mockito

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

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