android – getSupportActionBar()使用Robolectric返回null

当我通过Roboelectric和JUnit中的测试用例调用它时,方法getSupportActionBar()返回null.

这是我的简单测试用例:

package com.mobile.test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertthat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import android.app.Activity;
import android.content.Intent;
import com.mobile.android.core.R;
import com.mobile.android.core.activity.MainActivity;
import com.mobile.android.core.activity.TestActivity;

@RunWith(RobolectricTestRunner.class)
public class NavigationDrawerTest {
private Activity activity;

@Test
public void testNavigationDrawer() {
    activity = Robolectric.buildActivity(MainActivity.class).create().get();
    String hello = activity.getResources().getString(R.string.drawer_open);
    System.out.println(hello);
    assertEquals(hello,"Menu");
}
}

这是我的Activity类:

public class MainActivity extends ActionBaractivity {
// Drawer related
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
String[] mDrawerOptions;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // enable ActionBar app icon to behave as action to toggle nav-drawer
    if (getSupportActionBar() != null) {
        getSupportActionBar().setdisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }
}
}

关于hwo的任何好主意都要解决这个问题?
我是否必须写一些影子活动,或者是否有人知道如何使用RObolectric解决这些操作栏问题?

谢谢你的帮助

解决方法

支持ActionBar
通过使用Gingerbread sdk内部版本号为我的测试添加@Config注释,我能够获得支持ActionBar的实例:
@Test @Config(reportSdk = 10)
public void actionbartest(){
.... Your Test here
}

这里可以看到一个简单的项目设置:simple-robolectric

ActionBarSherlock
您必须将修改后的ActionBarSherlock文件添加到测试包中,并在@Before方法调用以下方法

ActionBarSherlock.registerImplementation(ActionBarSherlockRobolectric.class);
ActionBarSherlock.unregisterImplementation(ActionBarSherlockNative.class);
ActionBarSherlock.unregisterImplementation(ActionBarSherlockCompat.class);

完整的说明可在此处找到:ActionBar and Robolectric working together

更新使用Robolectric 2.2,您只需将配置注释“@Config(reportSdk = 10)”添加到您的测试方法或类中,它也应该可以正常工作.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...