简体   繁体   中英

Androidx : How to test Slider in UI tests (Espresso)?

How can I perform actions on slider (move cursor)?

How can I check slider value?

Are there any existing functions for this?

Slider look like that:

<com.google.android.material.slider.Slider
            android:id="@+id/sliderRating"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stepSize="1"
            android:valueFrom="1.0"
            android:valueTo="5.0" />

And Espresso check: onView(withId(R.id.sliderRating)).check( -> TODO <- )

It's easy to create a couple of methods to do that.

Here is what I have:

fun withValue(expectedValue: Float): Matcher<View?> {
    return object : BoundedMatcher<View?, Slider>(Slider::class.java) {
        override fun describeTo(description: Description) {
            description.appendText("expected: $expectedValue")
        }

        override fun matchesSafely(slider: Slider?): Boolean {
            return slider?.value == expectedValue
        }
    }
}

fun setValue(value: Float): ViewAction {
    return object : ViewAction {
        override fun getDescription(): String {
            return "Set Slider value to $value"
        }

        override fun getConstraints(): Matcher<View> {
            return ViewMatchers.isAssignableFrom(Slider::class.java)
        }

        override fun perform(uiController: UiController?, view: View) {
            val seekBar = view as Slider
            seekBar.value = value
        }
    }
}

The first one, the custom view matcher, is to test that the Slider has a specific value and the second one, the custom view action, is to set a new value.

A simple test example using them just to get the idea of how they work:

@Test
fun testSlider() {
    onView(withId(R.id.sliderRating)).check(matches(withValue(1.0F)))

    onView(withId(R.id.sliderRating)).perform(setValue(2.0F))

    onView(withId(R.id.sliderRating)).check(matches(withValue(2.0F)))
}

This test checks first of all if the slider has value 1.0, then changes its value to 2.0 and uses the matcher to check that the value is now 2.0.

I have the code in kotlin but if you need it in java it can be easily transformed (android studio can do that). As the question is not tagged with the language I don't know which one do you need, tag it next time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM