ActivityUnitTestCase and startActivity with ActionBarActivity

╄→尐↘猪︶ㄣ 提交于 2019-11-30 08:18:21

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

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.

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.

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.

Peter Lamberg

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!