Use times(1)
to verify a method is called exactly once.
verify(orderService, times(1)).getOrder(anyLong());
verify(orderService, times(1)).createOrder(any(CreateOrderRequest.class));
The above code verifies that both getOrder
and createOrder
are called exactly once on orderService
.
If the times(1)
in above example is replaced by only()
, the test would fail.
As per Mockito Javadoc of only()
,
Allows checking if given method was the only one invoked
verify(mock, only()).someMethod();
is same as
verify(mock).someMethod();
verifyNoMoreInteractions(mock);
i.e.
verify(mock, times(1)).someMethod();
verifyNoMoreInteractions(mock);
Therefore,
verify(orderService, only()).getOrder(anyLong());
verify(orderService, only()).createOrder(any(CreateOrderRequest.class));
is equivalent to
verify(orderService, times(1)).getOrder(anyLong()); // L1
verifyNoMoreInteractions(orderService); // L2
verify(orderService, times(1)).createOrder(any(CreateOrderRequest.class)); // L3
verifyNoMoreInteractions(orderService); // L4
It would fail at line “L2”.