gpt4 book ai didi

android - 使用 Robolectric 测试菜单

转载 作者:行者123 更新时间:2023-11-29 16:55:33 25 4
gpt4 key购买 nike

我目前正在学习 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?我是否遗漏了任何依赖项?

最佳答案

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

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

或者您可以确保 Activity 可见

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

From docs

这是什么 visible() 废话?

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
(amongst other unexpected behavior). The Activity’s hierarchy is attached to the Window on a device or emulator after onPostResume() on the Activity. Rather than make assumptions about when the visibility should be updated, Robolectric puts the power in the developer’s hands when writing tests.

So when do you call it? 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?

关于android - 使用 Robolectric 测试菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45146391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com