使用Robolectric模拟单击菜单项时出错

时间:2014-06-19 10:32:24

标签: android unit-testing robolectric

我正在探索用于测试Android应用的Robolectric功能,我进行了一个简单的单元测试,以验证执行点击菜单项时活动NoteEditor class是否打开。代码是:

    @Before
    public void setup(){
    //
    mProvider = new NotePadProvider();
    mContentResolver = Robolectric.application.getContentResolver();
    mProvider.onCreate();
    ShadowContentResolver.registerProvider(NotePad.AUTHORITY, mProvider);
    activity = Robolectric.buildActivity(NotesList.class).create().start().resume().visible().get();
}

    @Test
    public void menuAddShouldStartTheEditorActivity() throws Exception {
    // create reference to menu item "menu_add"
    MenuItem item = new TestMenuItem(R.id.menu_add);
    // simulate click item
    activity.onOptionsItemSelected(item);
    ShadowActivity shadowActivity = shadowOf(activity);
    // get next started activity
    Intent startedIntent = shadowActivity.getNextStartedActivity();
    ShadowIntent shadowIntent = Robolectric.shadowOf(startedIntent);

    assertThat(shadowIntent.getComponent().getClassName(), equalTo(NoteEditor.class.getName()));
}`

只有第一段代码才能正常工作,但是当我执行代码行时:
ShadowIntent shadowIntent = Robolectric.shadowOf(startedIntent);

Robolectric给我

[Error]: java.lang.NullPointerException
    at com.example.roboelectric.notepadtest.SimpleTest.menuAddShouldStartTheEditorActivity(SimpleTest.java:100)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source) (...)

任何想法为什么?提前致谢

2 个答案:

答案 0 :(得分:1)

我解决了它绕过组件并使用intent来验证正确的活动生命周期,所以我的测试用例变成了

@Test
public void menuAddShouldStartTheEditorActivity() throws Exception {
// create reference to menu item "menu_add"
MenuItem item = new TestMenuItem(R.id.menu_add);
// simulate click item
activity.onOptionsItemSelected(item);
ShadowActivity shadowActivity = shadowOf(activity);
// get next started intent from shadow
Intent startedIntent = shadowActivity.getNextStartedActivity();
// define expected intent (Editor class)
Intent expectedIntent = new Intent(Intent.ACTION_INSERT, NoteColumns.CONTENT_URI);
// verify it 
assertThat(startedIntent, equalTo(expectedIntent));
}

我不知道为什么,但getComponent()始终为null,因为AUT下一个活动(编辑)中的onCreate()永远不会被Robolectric执行。

答案 1 :(得分:0)

你不需要采取意图的阴影。只需:

Intent startedIntent = shadowActivity.getNextStartedActivity();
assertThat(startedIntent.getComponent().getClassName(), equalTo(NoteEditor.class.getName()));