0

I have a list of Object

List<MyClass> list = <an array of MyClass instances>

The MyClass class contains a method invokeMe();

Is there any way I can verify that the invokeMe method is called on one and only one of these MyClass instances in the list using Mockito?

Any of these classes could be called as they are accessed by different threads.v

ZZZ
  • 645
  • 4
  • 17

1 Answers1

0

Assuming I correctly understood your question you can do this as follows:

(...)

@Mock
MyClass mock1;

@Mock
MyClass mock2;

@Mock
MyClass mock3;

private List<MyClass> list = Arrays.asList(mock1, mock2, mock3);

(...)

@Test
public void whatever() {
  (...)

  verify(this.mock1, times(1)).invokeMe();
  verify(this.mock2, never()).invokeMe();
  verify(this.mock3, never()).invokeMe();
}
João Dias
  • 16,277
  • 6
  • 33
  • 45
  • Thanks. Your test assumes mock1 is called. But I would like to treat the test as pass if any one of these three mocks is invoked. – ZZZ Sep 27 '21 at 15:59
  • I don't think you can easily do that. Unless you try some kind of nested try-catch with all the possible combinations for that, I don't really think you have a clean way to do that. – João Dias Sep 27 '21 at 16:27