Last active
April 9, 2019 20:30
-
-
Save ufuk/7fd10c52bf0997b97cde to your computer and use it in GitHub Desktop.
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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