Albert Gao
Albert Gao

Reputation: 3773

How to solve this CalledFromWrongThreadException when doing android espresso test?

I got an error when doing espresso test

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6891) at android.view.ViewRootImpl.playSoundEffect(ViewRootImpl.java:5751) at android.view.View.playSoundEffect(View.java:20321) at android.view.View.performClick(View.java:5636) at nz.salect.handset.auth.EntryActivityUITest.should_open_logDetails_activity_when_pressing_logDetails_button(EntryActivityUITest.kt:47)

The line 47 is the code in the second tests where it tries to perform a click operation.

The 1st test passes where the 2nd failed because it can't even run due to the exception.

@LargeTest
@RunWith(AndroidJUnit4::class)
class EntryActivityUITest {
    @Rule
    @JvmField
    val entryAuthActivityRule = ActivityTestRule(EntryActivity::class.java, true, false)

    @Test
    fun it_should_show_logDetails_buttons_after_starting() {
        entryAuthActivityRule.launchActivity(null)

        Espresso.onView(ViewMatchers.withId(R.id.auth_button_logDetails))
            .check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
    }

    @Test
    fun should_open_logDetails_activity_after_pressing_logDetails_button() {
        entryAuthActivityRule.launchActivity(null)

        val button = entryAuthActivityRule.activity.findViewById<Button>(R.id.auth_button_logDetails)
        button.performClick()

        Espresso.onView(ViewMatchers.withId(R.id.loginDetails_textEdit_password))
            .check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
    }
}

What happens here? And how to solve it?

Upvotes: 1

Views: 387

Answers (1)

Blackbelt
Blackbelt

Reputation: 157447

those two lines

    val button = entryAuthActivityRule.activity.findViewById<Button>(R.id.auth_button_logDetails)
    button.performClick()

look suspicious. I would have expected something like

Espresso.onView(ViewMatchers.withId(R.id.auth_button_logDetails)).perform(ViewActions.click())

Upvotes: 4

Related Questions