androidkotlinandroid-espressoend-to-enduitest

How to get the tag of a view in an Espresso test?


I am working in some end to end test using Espresso.
In the test I need to know the user id (because I need to call one endpoint that mocks some external party).
To get the user id, I was thinking about setting it as a tag in a view and get the tag with Espresso.

Is there a way to do that?

I only find ways to get a view by tag, but not actually getting the content of the tag.

Thanks for your help.


Solution

  • You can use the following extension function:

    inline fun <reified T : Any> ViewInteraction.getTag(): T? {
        var tag: T? = null
        perform(object : ViewAction {
            override fun getConstraints() = ViewMatchers.isAssignableFrom(View::class.java)
    
            override fun getDescription() = "Get tag from View"
    
            override fun perform(uiController: UiController, view: View) {
                when (val viewTag = view.tag) {
                    is T -> tag = viewTag
                    else -> error("The tag cannot be casted to the given type!")
                }
            }
        })
        return tag
    }
    

    To the get tag like:

    @Test
    fun myTest() {
        ...
        val userId = onView(withId(R.id.myView)).getTag<String>()
        ...
    }