Tom Tucker
Tom Tucker

Reputation: 11916

Mockito: Verify a method is called at a specific point

Suppose calling bar() on a Foo object will in turn call baz() on its Waldo object, only in the first time. In other words,

Foo foo = new Foo();
foo.setWaldo(new Waldo());
foo.bar(); // This calls baz() on the Waldo.
foo.bar(); // This should not call baz() on the Waldo.

This is how I verify the call on baz() at the moment.

Foo foo = new Foo();
Waldo waldo = mock(Waldo.class);
foo.setWaldo(waldo);
foo.bar();
foo.bar();
verify(waldo).baz();

The problem with this is it doesn't verify when baz() was called. This would get a pass even if baz() gets called the second time foo.bar() is called.

How would verify this properly with Mockito?

Upvotes: 1

Views: 168

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79877

Foo foo = new Foo();
Waldo waldo = mock(Waldo.class);
foo.setWaldo(waldo);
foo.bar();
verify(waldo).baz();
foo.bar();
verifyNoMoreInteractions(waldo);

Upvotes: 4

Related Questions