2017-07-17 136 views
1

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

我的代码如下

@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?我错过任何依赖关系吗?

回答

3

onCreateOptionsMenuoncreate后调用,从而确保您可以看到您的菜单尝试

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(其他意想不到的 行为)。活动的层次结构在活动上的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?

+1

什么最让我为。可见()而不是.resume()。谢谢! –