Skip to content Skip to sidebar Skip to footer

ActivityUnitTestCase And StartActivity With ActionBarActivity

I try to test a Activity which uses ActionBarActivity (from the appcompat library). I need a custom Application to be able to manipulate the DI system to load my test service inste

Solution 1:

The accepted answer didn't work in my case, but including something this in the ActicityUnitTestCase subclass worked for me:

@Override
public void setUp(){
    ContextThemeWrapper context = new ContextThemeWrapper(getInstrumentation().getTargetContext(), R.style.AppTheme);
    setActivityContext(context);
}

Solution 2:

I found out that if I create a custom MockApplication and add the following code:

@Override
public void onCreate() {
    super.onCreate();
    setTheme(R.style.AppTheme);
}

I hope that will work for other people as well.


Solution 3:

Remember that we are supposed to create reusable activities and by setting the theme in the onCreate method we are connecting the activity to the AppTheme.

The answer of @Akira Speirs is the best option in my opinion even though we need to remember to update the test if the theme is changed in the AndroidManifest.


Solution 4:

ActivityUnitTestCase.startActivity calls setActivity prior to dispatching onCreate so code below does the trick:

@Override
protected void setActivity(Activity testActivity) {
    if (testActivity != null) testActivity.setTheme(R.style.AppTheme);
    super.setActivity(testActivity);
}

This could be an alternative to solution provided by @Akira Speirs for example if custom context needs to be used.


Solution 5:

In my case I was testing a custom component as part of a layout.

Just calling getActivity().setTheme(...) in the test's setUp() worked for me.

I was also getting this error when testing on a real device.

However testing with a API level 23 x86 emulator with HAXM enabled it works and is nice and fast.

Here is a more more complete setUp() method as an example:

@Override
public void setUp() throws Exception {

    super.setUp();

    startActivity(new Intent(getInstrumentation().getTargetContext(), Activity.class), null, null);

    getActivity().setTheme(R.style.MyAppTheme);

    getActivity().setContentView(R.layout.my_layout_under_test);

}

Post a Comment for "ActivityUnitTestCase And StartActivity With ActionBarActivity"