ericn
ericn

Reputation: 13103

Robolectric Handler post() not working as expected

I have the following code

class ClassToTest {
    fun doSomething() {
        Handler().post {
            println("some work by handler")
        }
    }
}

and the following test code

@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.N_MR1])
class TestClass {
    @Test
    fun `test do something`() {
        val underTest = ClassToTest()
        underTest.doSomething()
    }
}

My print statement or whatever inside Handler#post is apparently not getting called

Why?

Robolectric version 4.7.3 Java version 11 compileSdk 30

Upvotes: 0

Views: 391

Answers (1)

ericn
ericn

Reputation: 13103

Found the solution thanks to this post, adding shadowOf(getMainLooper()).idle() triggers the stuffs in inside post {}

@Test
    fun `test do something`() {
        val underTest = ClassToTest()
        underTest.doSomething()
        shadowOf(getMainLooper()).idle()
    }

Upvotes: 1

Related Questions