I'm using mockito to verify after each tests the number of interactions with my mocks. Some tests may have a lot of mocks so in order to avoid a long list of arguments when calling Mockito.verifyNoMoreInteractions I tried to add those mock to a list via Mockito.framework().addListener.
My test class
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyClass.class, MockitoConfig.class})
@SpringBootTest
public class MyClassTest {
@Autowired
private MyClass myClass;
@Autowired
private MockCollector mockCollector;
@MockBean
private MyMock myMock;
@After
public void after() {
verifyNoMoreInteractions(mockCollector.getMocks().toArray());
}
@Test
...
}
My configuration class
@Configuration
public class MockitoConfig {
@Bean
public MockCollector mockCollector() {
return new MockCollector();
}
public class MockCollector {
private final List<Object> createdMocks = new ArrayList<>();
public List<Object> getMocks() {
return createdMocks;
}
public MockCollector() {
Mockito.framework().addListener((MockCreationListener) (mock, settings) -> createdMocks.add(mock));
}
}
}
I created this configuration class so the whole addListener thing is only called once to avoid any RedundantListenerException.
The thing here is that my list of mocks is empty when queried in the after method. When I move the MockCollector's code directly in the after method it works great in the first test and obviously fails after the second because of a RedundantListenerException.
What am I missing here? Is there another way to perform what I want here?