我正在尝试编写Android Espresso测试来检查是否播放了视频。单击播放按钮后,正在检查SimpleExoPlayerView的关联播放器是否正在播放。问题在于,层次结构中还有一个PlaybackControlView,其ID与我的SimpleExoPlayerView相同(我从未设置过,所以我不知道它如何具有相同的ID)。如何指定我要测试SimpleExoPlayerView

这是我的测试:

@RunWith(AndroidJUnit4.class)
public class VideoPlaybackTest {

    @Rule
    public ActivityTestRule<MainActivity> mMainActivityTestRule =
            new ActivityTestRule<MainActivity>(MainActivity.class);

    @Before
    public void registerIdlingResources() {
        Espresso.registerIdlingResources(mMainActivityTestRule.getActivity().getIdlingResource());
    }

    @Test
    public void videoIsPlayed() {
        Intents.init();
        onView(withId(R.id.recipes_recycler_view))
                .perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
        onView(withId(R.id.steps_recycler_view))
                .perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
        onView(withId(R.id.exo_play))
                .perform(click());
        onView(withId(R.id.simple_video_view))
                .check(new VideoPlaybackAssertion(true));
        Intents.release();
    }

    @After
    public void unregisterIdlingResources() {
        Espresso.unregisterIdlingResources(mMainActivityTestRule.getActivity().getIdlingResource());
    }

}

class VideoPlaybackAssertion implements ViewAssertion {

    private final Matcher<Boolean> matcher;

    //Constructor
    public VideoPlaybackAssertion(Matcher<Boolean> matcher) {
        this.matcher = matcher;
    }

    //Sets the Assertion's matcher to the expected playbck state.
    public VideoPlaybackAssertion(Boolean expectedState) {
        this.matcher = is(expectedState);
    }

    //Method to check if the video is playing.
    @Override
    public void check(View view, NoMatchingViewException noViewFoundException) {
        if (noViewFoundException != null) {
            throw noViewFoundException;
        }

        SimpleExoPlayerView exoPlayerView = (SimpleExoPlayerView) view;
        SimpleExoPlayer exoPlayer = exoPlayerView.getPlayer();
        int state = exoPlayer.getPlaybackState();
        Boolean isPlaying;
        if ((state == STATE_BUFFERING) || (state == STATE_READY)) {
            isPlaying = true;
        } else {
            isPlaying = false;
        }
        assertThat(isPlaying, matcher);
    }

}



  android.support.test.espresso.AmbiguousViewMatcherException:'具有ID:
  com.example.android.bakingapp:id / simple_video_view'匹配多个
  层次结构中的视图。


具有相同ID的两个视图是我的SimpleExoPlayerView和我不太了解的PlaybackControlView

最佳答案

试试这个匹配器:

onView(allOf(withId(R.id.simple_video_view),
  withClassName(is(SimpleExoPlayerView.class.getName())))

08-05 00:48