如何在Espresso测试中获取视图的标签?

问题描述 投票:0回答:1

我正在使用Espresso进行一些端到端测试。在测试中,我需要知道用户ID(因为我需要调用一个模拟某个外部参与者的端点)。为了获得用户ID,我正在考虑将其设置为视图中的标签,并使用Espresso获得标签。

有没有办法做到这一点?

我只找到方法get a view by tag,但实际上没有获得标签的内容。

感谢您的帮助。

android kotlin android-espresso end-to-end uitest
1个回答
0
投票

您可以使用以下扩展功能:

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
}

然后获得标签,如:

val userId = onView(withId(R.id.myView)).getTag<String>()
© www.soinside.com 2019 - 2024. All rights reserved.