我是Android测试和使用Espresso的新手。我正在尝试测试,当用户单击RecyclerView中的项目时,将显示正确的数据。但是,当我尝试运行测试时,我得到的是空对象引用。谁能帮助我解决我做错的事情?
MyActivity.class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
cakeViewModel = ViewModelProviders.of(this).get(CakeViewModel.class);
if (cakeViewModel.cake.getValue() != null) {
cakeViewModel.cake.setValue(null);
}
retrieveData();
}
private void retrieveData() {
cakeViewModel.cake.setValue(null);
mainDb = Realm.getDefaultInstance();
Intent recipeIntent = getIntent();
int cakeId = recipeIntent.getIntExtra(MainActivity.CAKE_ID, 0);
Cake cake = mainDb.where(Cake.class).equalTo("id", cakeId).findFirst();
cakeViewModel.cake.setValue(cake);
getSupportActionBar().setTitle(cake.getName());
}
我的测试:
@RunWith(AndroidJUnit4.class)
public class RecipeActivityUITest {
@Rule
public ActivityTestRule<RecipeActivity> recipeActivityActivityTestRule = new ActivityTestRule<>(RecipeActivity.class);
@Test
public void clickOnRecyclerViewItem_opensRecipeStepActivity() {
onView(withId(R.id.rv_step_list)).check(matches(isDisplayed()));
onView(withId(R.id.rv_step_list)).perform(actionOnItemAtPosition(1, click()));
onView(withId(R.id.vp_step)).check(matches(isDisplayed()));
}
}
我遇到以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.ciaransloan.bakingapp.api.model.Cake.getName()' on a null object reference
at com.ciaransloan.bakingapp.RecipeActivity.retrieveData(RecipeActivity.java:108)
at com.ciaransloan.bakingapp.RecipeActivity.onCreate(RecipeActivity.java:53)
答案 0 :(得分:0)
原来,我的问题是我没有在测试中传递任何意图,因此当它试图加载对象时,它没有从意图中检索ID。毕竟问题与我的数据库无关。为了解决此问题,我将测试中的@Rule更改为以下内容:
@Rule
public ActivityTestRule<RecipeActivity> recipeActivityActivityTestRule = new ActivityTestRule<RecipeActivity>(RecipeActivity.class) {
@Override
protected Intent getActivityIntent() {
return new Intent(ApplicationProvider.getApplicationContext(), RecipeActivity.class).putExtra(MainActivity.CAKE_ID, 1);
}
};