In Espresso, how to avoid AmbiguousViewMatcherException when multiple views match

前端 未结 9 1474
情深已故
情深已故 2020-11-30 03:16

Having gridView which has some images. The gridView\'s cell comes out from same predefined layout, which has same id and desc.

R.id.item_image == 2131

9条回答
  •  误落风尘
    2020-11-30 03:35

    You can simply make NthMatcher like:

       class NthMatcher internal constructor(private val id: Int, private val n: Int) : TypeSafeMatcher(View::class.java) {
            companion object {
                var matchCount: Int = 0
            }
            init {
                var matchCount = 0
            }
            private var resources: Resources? = null
            override fun describeTo(description: Description) {
                var idDescription = Integer.toString(id)
                if (resources != null) {
                    try {
                        idDescription = resources!!.getResourceName(id)
                    } catch (e: Resources.NotFoundException) {
                        // No big deal, will just use the int value.
                        idDescription = String.format("%s (resource name not found)", id)
                    }
    
                }
                description.appendText("with id: $idDescription")
            }
    
            public override fun matchesSafely(view: View): Boolean {
                resources = view.resources
                if (id == view.id) {
                    matchCount++
                    if(matchCount == n) {
                        return true
                    }
                }
                return false
            }
        }
    

    Declare like this:

    fun withNthId(resId: Int, n: Int) = CustomMatchers.NthMatcher(resId, n)
    

    And use like this:

    onView(withNthId(R.id.textview, 1)).perform(click())
    

提交回复
热议问题