GetSupportActionBar () returns null using Robolectric

The getSupportActionBar () method returns null when I call it through a test case based on Roboelectric and JUnit.

This is my simple test case:

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

And this is my activity class:

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

Any bright ideas on hwo to fix this? Should I write some shadow activity, or does anyone know how to work with these problems in a bar with RObolectric ??

Thanks for any help

+7
android junit4 android-actionbar android-support-library robolectric
source share
1 answer

ActionBar Support
I managed to return an ActionBar support instance by adding the @Config annotation to my test with the gingerbread sdk build number:

 @Test @Config(reportSdk = 10) public void actionbarTest(){ .... Your Test here } 

A simple project setup can be seen here: simple-robolectric



ActionBarSherlock
You must add the modified ActionBarSherlock files to your test suite and call the following methods in the @Before method:

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

A complete set of instructions can be found here: ActionBar and Robolectric work together

Update
With Robolectric 2.2, you only need to add the configuration annotation β€œ@Config (reportSdk = 10)” to your test methods or class, and it should work as well.

+5
source share

All Articles