【问题标题】:Testing Menu with Robolectric使用 Robolectric 测试菜单
【发布时间】:2017-07-17 14:04:18
【问题描述】:

我目前正在学习 Robolectric 以测试 Android,但我无法获取我的应用程序菜单。 现在,Robolectric 的 getOptionsMenu() 正在返回 null。代码本身运行良好,但测试总是为选项菜单返回 null。

我的代码如下

@Test
public void onCreateShouldInflateTheMenu() {
    Intent intent = new Intent();
    intent.setData(Uri.EMPTY);
    DetailActivity dActivity = Robolectric.buildActivity(DetailActivity.class, intent).create().get();

    Menu menu = Shadows.shadowOf(dActivity).getOptionsMenu(); // menu is null

    MenuItem item = menu.findItem(R.id.action_settings); // I get a nullPointer exception here
    assertEquals(menu.findItem(R.id.action_settings).getTitle().toString(), "Settings");
}

有人知道为什么 Robolectric 返回 null 吗?我错过了任何依赖项吗?

【问题讨论】:

    标签: android unit-testing robolectric


    【解决方案1】:

    onCreateOptionsMenu 将在 oncreate 之后调用,以确保您可以看到您的菜单尝试

    Robolectric.buildActivity(DetailActivity.class, intent).create().resume().get();
    

    或者你可以确保活动是可见的

    Robolectric.buildActivity(DetailActivity.class, intent).create().visible().get();
    

    From docs

    这是什么可见的()废话?

    Turns out that in a real Android app, the view hierarchy of an Activity is not attached to the Window until sometime after onCreate() is called. Until this happens, the Activity’s views do not report as visible. This means you can’t click on them(以及其他意想不到的 行为)。 Activity 的层次结构附加到 Window 上 Activity 上的 onPostResume() 之后的设备或模拟器。而不是 对何时应该更新可见性做出假设, Robolectric 在编写时将权力交到开发人员手中 测试。

    那么你什么时候调用它? Whenever you’re interacting with the views inside the Activity. Methods like Robolectric.clickOn() require that the view is visible and properly attached in order to function. You should call visible() after create().

    Android: When is onCreateOptionsMenu called during Activity lifecycle?

    【讨论】:

    • 对我帮助最大的是 .visible() 而不是 .resume()。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多