Skip to content

Instantly share code, notes, and snippets.

@CodyEngel
Forked from dpmedeiros/AndroidMockUtil.java
Last active April 24, 2024 16:34
Show Gist options
  • Save CodyEngel/cb692fa41ed8274177398b55f0ed41ae to your computer and use it in GitHub Desktop.
Save CodyEngel/cb692fa41ed8274177398b55f0ed41ae to your computer and use it in GitHub Desktop.
Mock main thread handler for use in Android unit tests (requires Mockito and PowerMock)
package <Whatever Package Ya Want Really>
import android.os.Handler
import io.mockk.every
import io.mockk.mockk
import java.util.concurrent.CountDownLatch
/**
* TestHandler provides a way to execute tests that require a [Handler].
*
* The intended use of this class is to create a new instance of a [TestHandler] within the test
* class. From there anywhere a [Handler] is needed, it should be provided through the [handler]
* property. When running the test, it should be executed through the [runBlocking] function.
*
* @property handler provides the test handler which ensures that the any [Runnable] is executed
* without any delay.
*/
class TestHandler {
private val latch = CountDownLatch(2)
val handler: Handler = mockk(relaxed = true) {
every { post(any()) } answers {
try {
val runnable = invocation.args[0] as Runnable?
runnable?.run()
} finally {
latch.countDown()
}
true
}
}
fun runBlocking(block: () -> Unit) {
try {
block()
} finally {
latch.countDown()
}
latch.await()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment