我正在尝试使用 AndroidJunit4 测试 RecyclerView,这是我的测试代码:
package com.kaushik.myredmart.ui;
// all includes
@RunWith(AndroidJUnit4.class)
public class ProductListActivityTest {
@Rule
public ActivityTestRule<ProductListActivity> rule = new ActivityTestRule<>(ProductListActivity.class);
@Test
public void ensureListViewIsPresent() throws Exception {
ProductListActivity activity = rule.getActivity();
View viewByIdw = activity.findViewById(R.id.productListView);
assertThat(viewByIdw,notNullValue());
assertThat(viewByIdw, instanceOf(RecyclerView.class));
RecyclerView productRecyclerView = (RecyclerView) viewByIdw;
RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
assertThat(adapter, instanceOf(ProductAdapter.class));
}
}
我在检查适配器时遇到问题。尽管productRecyclerView通过了非空测试和RecyclerView实例,但最后一行出现以下错误:
java.lang.AssertionError:
Expected: an instance of com.kaushik.myredmart.adapter.ProductAdapter
but: null
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
at org.junit.Assert.assertThat(Assert.java:956)
at org.junit.Assert.assertThat(Assert.java:923)
at com.kaushik.myredmart.ui.ProductListActivityTest.ensureListViewIsPresent(ProductListActivityTest.java:45)
代码中有什么问题?
从这一行来看:
预期:com.kaushik.myredmart.adapter.ProductAdapter 的实例
但是:空
人们可以得出这样的结论:
RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
returns null
,当没有执行时可能会发生productRecyclerView.setAdapter(adapter)
.
确保您在活动生命周期回调中正确设置适配器(即在onCreate()
)。在我看来,您正在某些操作/回调后创建和设置适配器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)