我正在探索用于测试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) (...)


知道为什么吗?提前致谢

最佳答案

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

@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执行。

关于android - 使用Robolectric模拟单击菜单项时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24304457/

10-12 00:19