我试图为一个非常简单的应用程序编写单元测试。这是menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item android:id="@+id/action_settings" android:title="@string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
<item android:id="@+id/action_refresh" android:title="@string/action_refresh"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
App运行良好,两个项目都显示出来。 MainActivity.xml可以清楚地找到它们,因为
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
工作正常。
我有来自ActivityInstrumentationTestCase2
的单元测试,其中一个检查menu_main.xml。
public void testSettingsMenuItemExists() {
Object view = activity.findViewById(R.id.action_settings);
assertNotNull("Settings menu item does not exist", view);
}
显然存在 R.id.action_settings
因为代码编译,但是当测试运行时,它们找不到项目。他们确实从activity_main.xml中找到了元素。我尝试通过activity.getActionBar()
获取操作栏,它为空。我想也许操作栏可能是应用程序所有,而不是活动,但应用程序甚至没有getActionBar()
。
如何找到菜单项,以便我可以在单元测试中测试它们?
答案 0 :(得分:0)
我认为您必须在Manifest文件中声明具有主题的活动类,其中操作栏默认为..
<activity
android:name="com.example.MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.Light"/>
then you can get the action bar and it will not null.