7

当我通过基于 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");
}
}

这是我的活动课程:

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);
    }
}
}

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

谢谢你的帮助

4

1 回答 1

5

支持 ActionBar
我能够通过使用 Gingerbread sdk 内部版本号向我的测试添加 @Config 注释来取回 Support 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 和 Robolectric 一起工作

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

于 2013-08-03T15:40:27.230 回答