How to use MotionEvents method of androidx.test.espresso.action class

Best Appium-espresso-driver code snippet using androidx.test.espresso.action.MotionEvents

DragViewAction.kt

Source:DragViewAction.kt Github

copy

Full Screen

...5import androidx.test.espresso.PerformException6import androidx.test.espresso.UiController7import androidx.test.espresso.ViewAction8import androidx.test.espresso.action.CoordinatesProvider9import androidx.test.espresso.action.MotionEvents10import androidx.test.espresso.action.PrecisionDescriber11import androidx.test.espresso.action.Swiper12import androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed13import androidx.test.espresso.util.HumanReadables14import org.hamcrest.Matcher15import org.hamcrest.core.AllOf.allOf16/**17 * The number of move events to send for each drag.18 */19private const val DRAG_STEP_COUNT = 1020/**21 * Duration between the last move event and the up event, in milliseconds.22 */23private const val WAIT_BEFORE_SENDING_UP_MS = 40024/**25 * A custom [ViewAction] that can be replicate the long press & drag action for espresso.26 *27 * Reference: https://android.googlesource.com/platform/frameworks/base/+/2ff41d4/core/tests/coretests/src/android/widget/espresso/DragAction.java28 */29class DragViewAction(30 private val startCoordinatesProvider: CoordinatesProvider,31 private val endCoordinatesProvider: CoordinatesProvider,32 private val precisionDescriber: PrecisionDescriber33) : ViewAction {34 // Factor 1.5 is needed, otherwise a long press is not safely detected.35 private val longPressTimeout = (ViewConfiguration.getLongPressTimeout() * 1.5f).toLong()36 override fun getDescription(): String = "long press and drag"37 override fun getConstraints(): Matcher<View> = allOf(isCompletelyDisplayed())38 override fun perform(uiController: UiController, view: View) {39 val startCoordinates = startCoordinatesProvider.calculateCoordinates(view)40 val endCoordinates = endCoordinatesProvider.calculateCoordinates(view)41 val precision = precisionDescriber.describePrecision()42 val downEvent = MotionEvents.sendDown(uiController, startCoordinates, precision).down43 var status: Swiper.Status44 try {45 uiController.loopMainThreadForAtLeast(longPressTimeout)46 val steps = interpolate(startCoordinates, endCoordinates)47 steps.forEachIndexed { _, step ->48 if (!MotionEvents.sendMovement(uiController, downEvent, step)) {49 MotionEvents.sendCancel(uiController, downEvent)50 status = Swiper.Status.FAILURE51 }52 }53 // Wait before sending up because some drag handling logic may discard move events54 // that has been sent immediately before the up event.55 uiController.loopMainThreadForAtLeast(WAIT_BEFORE_SENDING_UP_MS.toLong())56 status = if (!MotionEvents.sendUp(uiController, downEvent, endCoordinates)) {57 MotionEvents.sendCancel(uiController, downEvent)58 Swiper.Status.FAILURE59 } else {60 Swiper.Status.SUCCESS61 }62 } catch (re: RuntimeException) {63 // Using a RuntimeException because of the swiper class which generally throws a64 // Runtime Exception.65 throw PerformException.Builder()66 .withActionDescription(description)67 .withViewDescription(HumanReadables.describe(view))68 .withCause(re)69 .build()70 } finally {71 downEvent.recycle()...

Full Screen

Full Screen

CardFragmentTest.kt

Source:CardFragmentTest.kt Github

copy

Full Screen

...6import androidx.test.core.app.ActivityScenario7import androidx.test.espresso.Espresso.onView8import androidx.test.espresso.UiController9import androidx.test.espresso.ViewAction10import androidx.test.espresso.action.MotionEvents11import androidx.test.espresso.action.ViewActions.*12import androidx.test.espresso.assertion.ViewAssertions.matches13import androidx.test.espresso.contrib.RecyclerViewActions14import androidx.test.espresso.matcher.ViewMatchers.*15import org.hamcrest.Matcher16import org.hamcrest.Matchers17import org.junit.Assert18import org.junit.Before19import org.junit.Test20private const val TIME_TO_LOAD_CARDS = 4600L21private const val TIME_TO_CHANGE_CARD = 2600L22class CardFragmentTest {23 @Before24 fun setup() {25 ActivityScenario.launch(MainActivity::class.java)26 onView(withId(R.id.random_button)).perform(click())27 Thread.sleep(TIME_TO_LOAD_CARDS)28 }29 @Test30 fun randomDeckButton() {31 onView(withId(R.id.card_list))32 .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0, click()))33 .check(matches(isDisplayed()))34 onView(withId(R.id.random_button)).check(matches(isNotEnabled()))35 Thread.sleep(TIME_TO_LOAD_CARDS)36 onView(withId(R.id.random_button)).check(matches(isEnabled()))37 onView(withId(R.id.random_button)).perform(click())38 Thread.sleep(TIME_TO_LOAD_CARDS)39 onView(withId(R.id.random_button)).check(matches(isEnabled()))40 }41 @Test42 fun changeCards() {43 for (i in 0..7) {44 onView(withId(R.id.card_list))45 .perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(i, click()))46 Thread.sleep(TIME_TO_CHANGE_CARD)47 }48 }49 @Test50 fun dragAndDrop() {51 onView(withId(R.id.card_list))52 .perform(dragAndMoveRightAndAssertMove(100f, 1f))53 }54 private fun createScreenShot(view: View): Bitmap {55 val bitmap = Bitmap.createBitmap(56 view.width,57 view.height, Bitmap.Config.ARGB_888858 )59 val canvas = Canvas(bitmap)60 view.draw(canvas)61 return bitmap62 }63 private fun dragAndMoveRightAndAssertMove(x: Float, y: Float): ViewAction {64 return object : ViewAction {65 override fun getConstraints(): Matcher<View> =66 Matchers.allOf(67 isAssignableFrom(RecyclerView::class.java),68 isDisplayed()69 )70 override fun getDescription(): String = String()71 override fun perform(uiController: UiController, view: View) {72 val location = IntArray(2)73 view.getLocationOnScreen(location)74 val screenShotBefore = createScreenShot(view).getPixel(view.x.toInt(), view.y.toInt())75 val coordinates = floatArrayOf(x + location[0], y + location[1])76 val toCoordinates = floatArrayOf(x + location[0] + 450f, y + location[1])77 val precision = floatArrayOf(1f, 1f)78 val down: MotionEvent = MotionEvents.sendDown(uiController, coordinates, precision).down79 uiController.loopMainThreadForAtLeast(2000)80 MotionEvents.sendDown(uiController, coordinates, precision).longPress81 MotionEvents.sendMovement(uiController, down, toCoordinates)82 MotionEvents.sendUp(uiController, down, coordinates)83 val screenShotAfter = createScreenShot(view).getPixel(view.x.toInt(), view.y.toInt())84 Assert.assertNotEquals(screenShotBefore, screenShotAfter)85 }86 }87 }88}...

Full Screen

Full Screen

DragAndDropViewAction.kt

Source:DragAndDropViewAction.kt Github

copy

Full Screen

...4import androidx.recyclerview.widget.RecyclerView5import androidx.test.espresso.UiController6import androidx.test.espresso.ViewAction7import androidx.test.espresso.action.GeneralLocation8import androidx.test.espresso.action.MotionEvents9import androidx.test.espresso.action.Press10import androidx.test.espresso.matcher.ViewMatchers11import org.hamcrest.Matcher12import org.hamcrest.core.AllOf13class DragAndDropViewAction(private val sourceViewPosition: Int,14 private val targetViewPosition: Int) : ViewAction {15 override fun getConstraints(): Matcher<View> {16 return AllOf.allOf(17 ViewMatchers.isDisplayed(),18 ViewMatchers.isAssignableFrom(RecyclerView::class.java)19 )20 }21 override fun getDescription(): String {22 return "Drag and drop action"23 }24 override fun perform(uiController: UiController, view: View) {25 val recyclerView: RecyclerView = view as RecyclerView26 //Sending down27 recyclerView.scrollToPosition(sourceViewPosition)28 uiController.loopMainThreadUntilIdle()29 val sourceView = recyclerView.findViewHolderForAdapterPosition(sourceViewPosition)?.itemView30 val sourceViewCenter = GeneralLocation.VISIBLE_CENTER.calculateCoordinates(sourceView)31 val fingerPrecision = Press.FINGER.describePrecision()32 val downEvent = MotionEvents.sendDown(uiController, sourceViewCenter, fingerPrecision).down33 try {34 // Factor 1.5 is needed, otherwise a long press is not safely detected.35 val longPressTimeout = (ViewConfiguration.getLongPressTimeout() * 1.5f).toLong()36 uiController.loopMainThreadForAtLeast(longPressTimeout)37 //Drag to the position38 recyclerView.scrollToPosition(targetViewPosition)39 uiController.loopMainThreadUntilIdle()40 val targetView = recyclerView.findViewHolderForAdapterPosition(targetViewPosition)?.itemView41 val targetViewLocation = if (targetViewPosition > sourceViewPosition) {42 GeneralLocation.BOTTOM_CENTER.calculateCoordinates(targetView)43 } else {44 GeneralLocation.TOP_CENTER.calculateCoordinates(targetView)45 }46 val steps = interpolate(sourceViewCenter, targetViewLocation)47 for (i in 0 until steps.size) {48 if (!MotionEvents.sendMovement(uiController, downEvent, steps[i])) {49 MotionEvents.sendCancel(uiController, downEvent)50 }51 }52 //Release53 if (!MotionEvents.sendUp(uiController, downEvent, targetViewLocation)) {54 MotionEvents.sendCancel(uiController, downEvent)55 }56 } finally {57 downEvent.recycle()58 }59 }60 // multiplier for full distance from start to end position to separate into steps61 private val SWIPE_EVENT_COUNT = 1062 private fun interpolate(start: FloatArray, end: FloatArray): Array<FloatArray> {63 val coord = Array(SWIPE_EVENT_COUNT) { FloatArray(2) }64 for (i in 1..SWIPE_EVENT_COUNT) {65 // get coordinates for each step (step = distance (end - start) / multiplier)66 // for x value67 coord[i - 1][0] = start[0] + (end[0] - start[0]) * i / SWIPE_EVENT_COUNT68 // for y value...

Full Screen

Full Screen

SlowerSwipe.kt

Source:SlowerSwipe.kt Github

copy

Full Screen

1package com.hendraanggrian.material.subtitlecollapsingtoolbarlayout2import android.os.SystemClock3import android.util.Log4import androidx.test.espresso.UiController5import androidx.test.espresso.action.MotionEvents.sendCancel6import androidx.test.espresso.action.MotionEvents.sendDown7import androidx.test.espresso.action.MotionEvents.sendMovement8import androidx.test.espresso.action.MotionEvents.sendUp9import androidx.test.espresso.action.Swiper10import androidx.test.espresso.action.Swiper.Status.FAILURE11import androidx.test.espresso.action.Swiper.Status.SUCCESS12import androidx.test.espresso.core.internal.deps.guava.base.Preconditions13/**14 * @see androidx.test.espresso.action.Swipe15 */16class SlowerSwipe : Swiper {17 override fun sendSwipe(18 uiController: UiController,19 startCoordinates: FloatArray,20 endCoordinates: FloatArray,21 precision: FloatArray22 ): Swiper.Status = sendLinearSwipe(uiController, startCoordinates, endCoordinates, precision,...

Full Screen

Full Screen

DragAndDropAction.kt

Source:DragAndDropAction.kt Github

copy

Full Screen

...5import androidx.recyclerview.widget.RecyclerView6import androidx.test.espresso.UiController7import androidx.test.espresso.ViewAction8import androidx.test.espresso.action.GeneralLocation9import androidx.test.espresso.action.MotionEvents10import androidx.test.espresso.action.Press11import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom12import androidx.test.espresso.matcher.ViewMatchers.isDisplayed13import org.hamcrest.Matcher14import org.hamcrest.Matchers.allOf15class DragAndDropAction(16 private val sourceViewPosition: Int,17 private val targetViewPosition: Int,18 @IdRes private val dragHandle: Int = -119) : ViewAction {20 override fun getConstraints(): Matcher<View> {21 return allOf(isDisplayed(), isAssignableFrom(RecyclerView::class.java))22 }23 override fun getDescription(): String {24 return "Drag and drop action"25 }26 override fun perform(uiController: UiController, view: View) {27 val recyclerView: RecyclerView = view as RecyclerView28 // Sending down29 recyclerView.scrollToPosition(sourceViewPosition)30 uiController.loopMainThreadUntilIdle()31 val sourceHolder = recyclerView.findViewHolderForAdapterPosition(sourceViewPosition)32 val sourceItemView = checkNotNull(sourceHolder).itemView33 val sourceView = if (dragHandle < 0) sourceItemView else sourceItemView.findViewById(dragHandle)34 val sourceViewCenter = GeneralLocation.VISIBLE_CENTER.calculateCoordinates(sourceView)35 val fingerPrecision = Press.FINGER.describePrecision()36 val downEvent = MotionEvents.sendDown(uiController, sourceViewCenter, fingerPrecision).down37 try {38 val longPressTimeout = (ViewConfiguration.getLongPressTimeout() * 2f).toLong()39 uiController.loopMainThreadForAtLeast(longPressTimeout)40 recyclerView.scrollToPosition(targetViewPosition)41 uiController.loopMainThreadUntilIdle()42 val targetHolder = recyclerView.findViewHolderForAdapterPosition(targetViewPosition)43 val targetItemView = checkNotNull(targetHolder).itemView44 val targetView = if (dragHandle < 0) {45 targetItemView46 } else {47 targetItemView.findViewById(dragHandle)48 }49 val targetViewLocation = GeneralLocation.CENTER.calculateCoordinates(targetView)50 targetViewLocation[1] = targetViewLocation[1] + 1051 val steps = interpolate(sourceViewCenter, targetViewLocation)52 for (element in steps) {53 if (!MotionEvents.sendMovement(uiController, downEvent, element)) {54 MotionEvents.sendCancel(uiController, downEvent)55 }56 }57 if (!MotionEvents.sendUp(uiController, downEvent, targetViewLocation)) {58 MotionEvents.sendCancel(uiController, downEvent)59 }60 } finally {61 downEvent.recycle()62 }63 }64 private fun interpolate(start: FloatArray, end: FloatArray): Array<FloatArray> {65 val res = Array(SWIPE_EVENT_COUNT) { FloatArray(2) }66 for (i in 1..SWIPE_EVENT_COUNT) {67 res[i - 1][0] = start[0] + (end[0] - start[0]) * i / SWIPE_EVENT_COUNT68 res[i - 1][1] = start[1] + (end[1] - start[1]) * i / SWIPE_EVENT_COUNT69 }70 return res71 }72 companion object {...

Full Screen

Full Screen

ViewActions.kt

Source:ViewActions.kt Github

copy

Full Screen

...3import android.view.View4import androidx.test.espresso.UiController5import androidx.test.espresso.ViewAction6import androidx.test.espresso.action.GeneralLocation7import androidx.test.espresso.action.MotionEvents8import androidx.test.espresso.action.Press9import androidx.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast10import org.hamcrest.Matcher11private var sMotionEventDownHeldView: MotionEvent? = null12fun pressAndHold(): ViewAction {13 return PressAndHoldAction()14}15fun release(): ViewAction {16 return ReleaseAction()17}18private class PressAndHoldAction : ViewAction {19 override fun getConstraints(): Matcher<View> {20 return isDisplayingAtLeast(90) // Like GeneralClickAction21 }22 override fun getDescription(): String {23 return "Press and hold action"24 }25 override fun perform(uiController: UiController, view: View) {26 if (sMotionEventDownHeldView != null) {27 throw AssertionError("Only one view can be held at a time")28 }29 val precision = Press.FINGER.describePrecision()30 val coords = GeneralLocation.CENTER.calculateCoordinates(view)31 sMotionEventDownHeldView = MotionEvents.sendDown(uiController, coords, precision).down32 }33}34private class ReleaseAction : ViewAction {35 override fun getConstraints(): Matcher<View> {36 return isDisplayingAtLeast(90) // Like GeneralClickAction37 }38 override fun getDescription(): String {39 return "Release action"40 }41 override fun perform(uiController: UiController, view: View) {42 if (sMotionEventDownHeldView == null) {43 throw AssertionError("Before calling release(), you must call pressAndHold() on a view")44 }45 val coords = GeneralLocation.CENTER.calculateCoordinates(view)46 MotionEvents.sendUp(uiController, sMotionEventDownHeldView!!, coords)47 }48}

Full Screen

Full Screen

TouchMotionMatcher.kt

Source:TouchMotionMatcher.kt Github

copy

Full Screen

1package com.mojo.app.matchers2import android.view.View3import androidx.test.espresso.UiController4import androidx.test.espresso.ViewAction5import androidx.test.espresso.action.MotionEvents6import androidx.test.espresso.matcher.ViewMatchers.isDisplayed7import org.hamcrest.Matcher8fun moveFromTo(fromX: Float, fromY: Float, toX: Float, toY: Float): ViewAction {9 return object : ViewAction {10 override fun getConstraints(): Matcher<View> {11 return isDisplayed()12 }13 override fun getDescription(): String {14 return "Sending touch events."15 }16 override fun perform(uiController: UiController, view: View) {17 val location = IntArray(2)18 view.getLocationOnScreen(location)19 val coordinatesDown = floatArrayOf(fromX + location[0], fromY + location[1])20 val precision = floatArrayOf(1f, 1f)21 val down = MotionEvents.sendDown(uiController, coordinatesDown, precision).down22 uiController.loopMainThreadForAtLeast(300)23 MotionEvents.sendUp(uiController, down, coordinatesDown)24 val downTwice = MotionEvents.sendDown(uiController, coordinatesDown, precision).down25 uiController.loopMainThreadForAtLeast(300)26 val coordinatesMove = floatArrayOf(toX + location[0], toY + location[1])27 MotionEvents.sendMovement(uiController, downTwice, coordinatesMove)28 uiController.loopMainThreadForAtLeast(300)29 MotionEvents.sendUp(uiController, downTwice, coordinatesMove)30 }31 }32}...

Full Screen

Full Screen

ViewActionUtil.kt

Source:ViewActionUtil.kt Github

copy

Full Screen

1package com.lebartodev.lnote.utils2import android.view.View3import androidx.test.espresso.UiController4import androidx.test.espresso.ViewAction5import androidx.test.espresso.action.MotionEvents6import androidx.test.espresso.matcher.ViewMatchers.isDisplayed7import org.hamcrest.Matcher8object ViewActionUtil {9 fun touchDownAndUp(x: Float, y: Float): ViewAction {10 return object : ViewAction {11 override fun getConstraints(): Matcher<View> {12 return isDisplayed()13 }14 override fun getDescription(): String {15 return "Send touch events."16 }17 override fun perform(uiController: UiController, view: View) {18 val location = IntArray(2)19 view.getLocationOnScreen(location)20 val coordinates = floatArrayOf(x + location[0], y + location[1])21 val precision = floatArrayOf(1f, 1f)22 // Send down event, pause, and send up23 val down = MotionEvents.sendDown(uiController, coordinates, precision).down24 uiController.loopMainThreadForAtLeast(200)25 MotionEvents.sendUp(uiController, down, coordinates)26 }27 }28 }29}...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium-espresso-driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful