Skip to content

Instantly share code, notes, and snippets.

@ufuk ufuk/BaseMockitoTest.java
Last active Apr 9, 2019

Embed
What would you like to do?
Performs "verify no more interactions" check automatically for all mock objects (works with Mockito version 2). For detailed description: https://ufukuzun.wordpress.com/2019/04/09/ne-olup-bittiginden-habersiz-testlere-derman-mockscollector/ (Turkish)
import org.apache.commons.lang3.ArrayUtils;
import org.junit.After;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@RunWith(MockitoJUnitRunner.class)
public abstract class BaseMockitoTest {
private MockitoMocksCollector mockitoMocksCollector = new MockitoMocksCollector();
@After
public void after() {
Object[] allMocks = mockitoMocksCollector.getAllMocks();
if (ArrayUtils.isNotEmpty(allMocks)) {
verifyNoMoreInteractions(allMocks);
}
}
protected InOrder inOrderedVerifier() {
return inOrder(mockitoMocksCollector.getAllMocks());
}
}
import org.mockito.internal.listeners.CollectCreatedMocks;
import org.mockito.internal.progress.MockingProgress;
import org.mockito.internal.progress.ThreadSafeMockingProgress;
import java.util.LinkedList;
import java.util.List;
public final class MockitoMocksCollector {
private final List<Object> createdMocks;
public MockitoMocksCollector() {
createdMocks = new LinkedList<>();
MockingProgress mockingProgress = new ThreadSafeMockingProgress();
mockingProgress.setListener(new CollectCreatedMocks(createdMocks));
}
public Object[] getAllMocks() {
return createdMocks.toArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.