pleasehelpmeee
pleasehelpmeee

Reputation: 45

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...

For example, The numer of times that the Class.doSomething() was called: n times

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...

Can someone please help me with this?

Thanks!

Upvotes: 0

Views: 2422

Answers (2)

MarS
MarS

Reputation: 74

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

Upvotes: 1

xinglu
xinglu

Reputation: 66

  1. assume that you have a class Sample With method doSomehting
public class Sample {
    public void doSomething();
}
  1. in JUnit test case, verify the method was called n times using Mockito
@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

Upvotes: 3

Related Questions