Android Espresso: Make assertion while button is kept pressed

一笑奈何 提交于 2021-02-20 11:26:12

问题


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:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/32010927/android-espresso-make-assertion-while-button-is-kept-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!