Java mockito mock set

Perhaps this layout is installed after use in a loop, for example.

for(String key: mySet) { ...} 

Thanks.

+7
source share
2 answers

There are several options:

  • Paste it
  • Use @Mock annotation

Examples:

 Set<String> mySet = (Set<String>) mock(Set.class); 

- or -

 @Mock private Set<String> mySet; @Before public void doBefore() throws Exception { MockitoAnnotations.initMocks(this.getClass()); //this should create mocks for your objects... } 
+10
source

Although Nicholas's answer clearly explains how you are mocking Set, I think your question also implies that you want to mock the behavior of the set during the loop.

To do this, you first need to know that your code is only syntactic sugar and extends to:

 for (Iterator iterator = mySet.iterator(); iterator.hasNext();) { String key = (String) iterator.next(); ... } 

(For more on this, see the Stackoverflow question. Which is more efficient for each loop or iterator? )

This makes it clear that you need to make fun of the iterator() method. After you customize the layout as described by Nicholas, you mock the iterator as follows:

 when(mySet.iterator()).thenAnswer(new Answer<Iterator<String>>() { @Override public Iterator<String> answer(InvocationOnMock invocation) throws Throwable { return Arrays.asList("A", "B").iterator(); } }); 
+5
source

All Articles