我有一个片段,其中包含一个列表视图,该列表视图通过更改从我的应用程序的Room数据库检索的实时数据来动态填充。我想编写一个Espresso测试,可以单击此列表中的一个项目,但是无法弄清楚如何填充列表或动态设置其适配器。像这样:
@get:Rule
val activityTestRule = ActivityTestRule(MainActivity::class.java)
@Before
fun setup() {
activityTestRule.activity.findNavController(R.id.nav_host_fragment).navigate(R.id.session_list_fragment)
}
@Test
fun clickingSessionItemBringsUpOverlay() {
val sessions = listOf(Session(0, foreignId = 0, name ="test"))
val sessionListView = activityTestRule.activity.findViewById<ListView>(R.id.list_sessions)
sessionListView.adapter = SessionListAdapter(activityTestRule.activity, sessions)
onData(withId(R.id.list_sessions))
.inAdapterView(withId(R.id.list_sessions))
.atPosition(0)
.perform(click())
}
当前此错误为:
java.lang.IllegalStateException: Observer android.widget.AbsListView$AdapterDataSetObserver@1cbcb1b was not registered.
SessionListAdapter
只是一个自定义适配器,用于使用Session对象中的字段来设置视图。在片段中,通常按以下方式设置适配器:
private val sessionChangeObserver = Observer<List<Session>> {
it?.let {
sessionList = it
sessionAdapter = SessionListAdapter(activityContext, sessionList)
list_sessions.adapter = sessionAdapter
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
sessionListViewModel.getAllSessions().observe(viewLifecycleOwner, sessionChangeObserver)
activityContext = activity!!
}