Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
1
Indexable
Never
import android.view.View
import androidx.test.espresso.IdlingResource
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import org.hamcrest.Matcher

class HeaderVisibleIdlingResource(private val matcher: Matcher<View>) : IdlingResource {
    private var resourceCallback: IdlingResource.ResourceCallback? = null

    override fun getName(): String {
        return "HeaderVisibleIdlingResource"
    }

    override fun isIdleNow(): Boolean {
        val view = getView(matcher)
        val idle = view?.isShown ?: false

        if (idle) {
            resourceCallback?.onTransitionToIdle()
        }

        return idle
    }

    override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback?) {
        resourceCallback = callback
    }

    private fun getView(matcher: Matcher<View>): View? {
        val interaction = onView(matcher)
        val finderField = interaction.javaClass.getDeclaredField("viewFinder")
        finderField.isAccessible = true
        val viewFinder = finderField.get(interaction) as ViewFinder
        return viewFinder.view
    }
}

fun waitForHeader() {
    val idlingResource = HeaderVisibleIdlingResource(withId(R.id.header_title))
    try {
        IdlingRegistry.getInstance().register(idlingResource)
        onView(withId(R.id.header_title)).check(matches(isDisplayed()))
    } finally {
        IdlingRegistry.getInstance().unregister(idlingResource)
    }
}