Created
October 8, 2020 04:44
-
-
Save huuphuoc1396/f7b1fe723fb26307c184878a5db8db0f to your computer and use it in GitHub Desktop.
RecyclerView testing - Performing actions and matches on items by position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.content.res.Resources | |
| import android.view.View | |
| import androidx.recyclerview.widget.RecyclerView | |
| import org.hamcrest.Description | |
| import org.hamcrest.Matcher | |
| import org.hamcrest.TypeSafeMatcher | |
| /** | |
| * Performing actions and matches on items by position. | |
| * @see <a href="https://github.com/dannyroa/espresso-samples">Android Espresso Samples by Danny Roa</a> | |
| */ | |
| class RecyclerViewMatcher private constructor( | |
| private val recyclerViewId: Int | |
| ) { | |
| fun atPosition(position: Int): Matcher<View> { | |
| return atPositionOnView(position, -1) | |
| } | |
| fun atPositionOnView(position: Int, targetViewId: Int): Matcher<View> { | |
| return object : TypeSafeMatcher<View>() { | |
| private var resources: Resources? = null | |
| override fun describeTo(description: Description) { | |
| var idDescription = "$recyclerViewId" | |
| resources?.let { resources -> | |
| idDescription = try { | |
| resources.getResourceName(recyclerViewId) | |
| } catch (exception: Resources.NotFoundException) { | |
| "Resource name not found with @id/$recyclerViewId" | |
| } | |
| } | |
| description.appendText(idDescription) | |
| } | |
| override fun matchesSafely(view: View): Boolean { | |
| this.resources = view.resources | |
| val recyclerView: RecyclerView? = view.rootView.findViewById(recyclerViewId) | |
| val childView = recyclerView?.findViewHolderForAdapterPosition(position)?.itemView | |
| val targetView = if (targetViewId != -1) { | |
| childView?.findViewById(targetViewId) | |
| } else { | |
| childView | |
| } | |
| return view == targetView | |
| } | |
| } | |
| } | |
| companion object { | |
| fun withRecyclerView(recyclerViewId: Int): RecyclerViewMatcher { | |
| return RecyclerViewMatcher(recyclerViewId) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment