gpt4 book ai didi

java - Android RecyclerView Adapter 在单元测试中给出 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:39:20 28 4
gpt4 key购买 nike

我正在尝试使用 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)

代码有什么问题?

最佳答案

从这一行判断:

Expected: an instance of com.kaushik.myredmart.adapter.ProductAdapter but: null

可以得出这样的结论:

RecyclerView.Adapter adapter = productRecyclerView.getAdapter();

返回null,这可能发生在没有执行productRecyclerView.setAdapter(adapter)时。

确保您在 Activity 生命周期回调中正确设置了适配器(即在 onCreate() 中)。在我看来,您是在执行某些操作/回调后创建和设置适配器。

关于java - Android RecyclerView Adapter 在单元测试中给出 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43730887/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com