Skip to content

Instantly share code, notes, and snippets.

@muratcanbur
Forked from ufuk/BaseMockito2JUnit4Test.java
Last active April 15, 2019 10:50
Show Gist options
  • Save muratcanbur/5b444cbee118da48691b2771daa3c7ba to your computer and use it in GitHub Desktop.
Save muratcanbur/5b444cbee118da48691b2771daa3c7ba 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)
@RunWith(AndroidJUnit4::class)
abstract class BaseMockitoTest {
private val mockitoMocksCollector = MockitoMocksCollector()
@After
fun after() {
val allMocks = mockitoMocksCollector.getAllMocks()
allMocks.forEach { mock ->
verifyNoMoreInteractions(mock)
}
mockitoMocksCollector.close()
}
protected fun inOrderVerifier(): InOrder {
return inOrder(mockitoMocksCollector.getAllMocks())
}
}
class MockitoMocksCollector {
private var createdMocks: MutableList<Any> = ArrayList()
private var mockCreationListener: MockCreationListener
init {
val mockingProgress = ThreadSafeMockingProgress.mockingProgress()
mockCreationListener = MockCreationListener { mock, _ ->
createdMocks.add(mock)
}
mockingProgress.addListener(mockCreationListener)
}
fun close() {
Mockito.framework().removeListener(mockCreationListener)
}
fun getAllMocks(): MutableList<Any> {
return createdMocks
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment