5

I'm quite new to Espresso on Android and I am running into the following problem: I want Espresso to perform a longclick(or something..) on a button, and while the button is kept pressed down, I want to check the state of a different View.

In (more or less) pseudocode:

onView(withId(button_id)).perform(pressButtonDown());
onView(withId(textBox_id)).check(matches(withText("Button is pressed")));
onView(withId(button_id)).perform(releaseButton());

I tried writing 2 custom Taps, PRESS and RELEASE, with MotionEvents.sendDown() and .sendUp(), but did not get it to work. If this is the right path, I can post the code I've got so far.

Edit:

public class PressViewActions
{
    public static ViewAction pressDown(){
        return new GeneralClickAction(HoldTap.DOWN, GeneralLocation.CENTER, Press.THUMB);
    }

    public static ViewAction release() {
        return new GeneralClickAction(HoldTap.UP, GeneralLocation.CENTER, Press.THUMB);
    }
}

And the code for the Tappers:

public enum HoldTap implements Tapper {

    DOWN {
        @Override
        public Tapper.Status sendTap(UiController uiController, float[] coordinates, float[] precision)
        {
            checkNotNull(uiController);
            checkNotNull(coordinates);
            checkNotNull(precision);

            DownResultHolder res = MotionEvents.sendDown(uiController, coordinates, precision);

            ResultHolder.setController(uiController);
            ResultHolder.setResult(res);

            return Status.SUCCESS;
        }
    },

    UP{
        @Override
        public Tapper.Status sendTap(UiController uiController, float[] coordinates, float[] precision)
        {
            DownResultHolder res = ResultHolder.getResult();
            UiController controller = ResultHolder.getController();

            try {
                if(!MotionEvents.sendUp(controller, res.down))
                {
                    MotionEvents.sendCancel(controller, res.down);
                    return Status.FAILURE;
                }

            }
            finally {
                //res.down.recycle();
            }

            return Status.SUCCESS;
        }
    }
}

The error I get is the following:

android.support.test.espresso.PerformException: Error performing 'up click' on view 'with id: de.test.app:id/key_ptt'.
...
...
Caused by: java.lang.RuntimeException: Couldn't click at: 281.5,1117.5 precision: 25.0, 25.0 . Tapper: UP coordinate provider: CENTER precision describer: THUMB. Tried 3 times. With Rollback? false

I hope, this helps.

Any help and ideas will be appreciated!

Tanks a lot in advance!

1
  • I think the general idea should work, post the code for the custom taps Aug 15, 2015 at 7:28

1 Answer 1

10

A tap in Android is made up of two events, a down event and a up/cancel event. If you want to have these two as separate you cannot make "taps" as they already encompass both.

That said, your idea works, you just need to use a lower-level api, namely UiController along with the helper methods in MotionEvents. Be warned though: since "releasing" a view requires first holding on it, your tests will be dependent on each other if you don't do proper clean up.

Example: in a test you press a View, your test fails, then in another test you release on a view you didn't click: your second test would pass while it shouldn't have.

I uploaded on my github a complete sample. Here the keypoints. First the test code:

@Before
public void setUp() throws Exception {
    super.setUp();
    injectInstrumentation(InstrumentationRegistry.getInstrumentation());
    getActivity();
}

@After
public void tearDown() throws Exception {
    super.tearDown();
    LowLevelActions.tearDown();
}

@Test
public void testAssertWhilePressed() {
    onView(withId(R.id.button)).perform(pressAndHold());
    onView(withId(R.id.text)).check(matches(withText("Button is held down")));
    onView(withId(R.id.button)).perform(release());
}

Then LowLevelActions:

public class LowLevelActions {
    static MotionEvent sMotionEventDownHeldView = null;

    public static PressAndHoldAction pressAndHold() {
        return new PressAndHoldAction();
    }

    public static ReleaseAction release() {
        return new ReleaseAction();
    }

    public static void tearDown() {
        sMotionEventDownHeldView = null;
    }

    static class PressAndHoldAction implements ViewAction {
        @Override
        public Matcher<View> getConstraints() {
            return isDisplayingAtLeast(90); // Like GeneralClickAction
        }

        @Override
        public String getDescription() {
            return "Press and hold action";
        }

        @Override
        public void perform(final UiController uiController, final View view) {
            if (sMotionEventDownHeldView != null) {
                throw new AssertionError("Only one view can be held at a time");
            }

            float[] precision = Press.FINGER.describePrecision();
            float[] coords = GeneralLocation.CENTER.calculateCoordinates(view);
            sMotionEventDownHeldView = MotionEvents.sendDown(uiController, coords, precision).down;
            // TODO: save view information and make sure release() is on same view
        }
    }

    static class ReleaseAction implements ViewAction {
        @Override
        public Matcher<View> getConstraints() {
            return isDisplayingAtLeast(90);  // Like GeneralClickAction
        }

        @Override
        public String getDescription() {
            return "Release action";
        }

        @Override
        public void perform(final UiController uiController, final View view) {
            if (sMotionEventDownHeldView == null) {
                throw new AssertionError("Before calling release(), you must call pressAndHold() on a view");
            }

            float[] coords = GeneralLocation.CENTER.calculateCoordinates(view);
            MotionEvents.sendUp(uiController, sMotionEventDownHeldView, coords);
        }
    }
}
3
  • 1
    Thank you very much! Didn't have the time to really test it, but it looks very promising! At least, it doesn't give any errors ;)
    – stfn
    Aug 18, 2015 at 14:20
  • 1
    Thank you for giving this answer. It works great ! There is one thing I had to add though. Inside the perform method of the ReleaseAction class, I had to add " sMotionEventDownHeldView = null;" at the bottom of the method. Nov 9, 2015 at 18:59
  • The only way I could think to make this better would be to rename LowLevelActions to Finger May 22, 2019 at 13:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.