1
static class Foo {
    public void bar(int i) {}
}

@Test
public void foo() {
    Foo f = Mockito.spy(new Foo());
    f.bar(42);
    Mockito.verify(f, Mockito.times(1)).bar(42);
    f.bar(42);
    Mockito.verify(f, Mockito.times(1)).bar(42);
}

causes org.mockito.exceptions.verification.TooManyActualInvocations (wanted 1 time, but was 2) on last line. Running it in debug shows, that InvocationMatcher ignores the fact that first invocation was already verified. And it does not depend on witch exactly matcher is passed into bar. Am I doing something wrong, or it is a bug of Mockito?

Adamovskiy
  • 1,376
  • 1
  • 12
  • 42
  • Why not seperating it in 2 different test cases? – Albert Bos Sep 22 '16 at 12:20
  • Possible duplicate of [How to verify a method is called two times with mockito verify()](http://stackoverflow.com/questions/14889951/how-to-verify-a-method-is-called-two-times-with-mockito-verify) – Joe Sep 22 '16 at 12:21
  • 1
    @Joe I think it's not duplicate because the OP is verifying the same method twice. Have you tried reseting f after the first verify invocation: `Mockito.reset(f)` ? – troig Sep 22 '16 at 12:26

1 Answers1

5

There is no bug. The implementors of the library thinks multiple invocations in a single test method is not a best practice. There two choices to overcome this issue:

  1. Good one: use separate tests for each f.bar() invocations and test them independently.
  2. Not a good one: use Mockito.reset(f) before the second invocation. It resets the state of the spied f; for instance if you have inserted a mock call like doThrow(new Exception).when(f).bar(45), it is reset after the reset() call. But the second verify works with times(1).
mtyurt
  • 3,369
  • 6
  • 38
  • 57