在RecyclerView上进行浓缩咖啡测试

时间:2019-12-10 12:13:24

标签: android android-recyclerview junit4 android-espresso

我开始测试驱动的开发人员,但是一开始我就遇到了错误。 我不明白例外情况:

E/TestRunner: androidx.test.espresso.PerformException: Error performing 'actionOnItemAtPosition performing ViewAction: single click on item at position: 0' on view 'with id: com.jakchang.idus:id/recyclerView'. at blabla~
     Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
    (is assignable from class: class androidx.recyclerview.widget.RecyclerView and is displayed on the screen to the user)
    Target view: "RecyclerView{id=2131230893, res-name=recyclerView, visibility=VISIBLE, width=1080, height=0, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=android.widget.LinearLayout$LayoutParams@1a52327, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=0}"
        at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:252)
        at androidx.test.espresso.ViewInteraction.access$100(ViewInteraction.java:65)
        at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:158)
        at androidx.test.espresso.ViewInteraction$1.call

和下面的代码

@JvmField
@Rule
var mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)

@Test
fun recyclerTest(){
    onView(withId(R.id.homeIcon)).perform(click())
    onView(withId(R.id.recyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0,click()))
}

开始活动且仅使用

onView(withId(R.id.homeIcon)).perform(click())

似乎可以正常工作,但是执行以下行时

onView(withId(R.id.recyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0,click()))

出现错误。

层结构看起来像这样

constraint-layout
  -linear-layout
  --home_icon
 -scroll view
  --linear-layout
   ---recyclerview
   ---progressbar

我该如何解决?

1 个答案:

答案 0 :(得分:0)

问题可能是您可能必须先滚动ScrollView,直到向用户显示RecyclerView为止,然后再执行actionOnItemAtPosition指令。

尝试在此之前添加onView(withId(R.id.recyclerView)).perform(ViewActions.scrollTo());。测试将是:

@Test
fun recyclerTest(){
    onView(withId(R.id.homeIcon)).perform(click());
    onView(withId(R.id.recyclerView)).perform(ViewActions.scrollTo(),
       RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>(0,click()));
}