简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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