Is it possible in mockito to verify a method was called on a mock based on whether the mock was actually used in the unit-under-test?

For a simple example, I supply a mock factory (FooFactory) to my unit-under-test, and when Foo.create() is called, it returns a mock (Foo) to be used by certain methods in the unit-under-test. How can I verify that Foo.method() is called only if Foo.create() was called by the unit-under-test?

For a little more concrete example, my factory returns a Reader object that I want to ensure is closed, but not every method in the class actually constructs a Reader. I could obviously add the verification to every test where I know the Reader is needed, but that seems like a lot of duplicated effort.

+1. You could create separate unit test for both cases(eg. testWasInteraction, testNoInteraction) and do not have any other verification in cleanup methods. Bottom line - if you want this verification, write specific unit test. At the end, if there will be a bug, you would want to see one test failure, not multiple failures in each test case which uses this method.
–
Petro SemeniukDec 10 '10 at 0:07

Honestly it sounds like your test is tooo complicated. It's been my experience of many projects and lots of unit testing that the best way to handle things is to ensure that each test tests one thing only. You can have as many asserts as you like, but it should be one method being called and one scenario tested. Anything mo and the test becomes too complex. Plus it makes it very hard for other developers to pick up the test at a later stage when developing the app further.

So I'd suggest breaking your test up into multiple tests, one per scenario and then see if you still need this.