ActivityUnitTestCase and startActivity with Action

2019-02-05 22:05发布

问题:

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 instead of the real service.

If I have my test written and call startActivity I get the following error:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

If I call launchActivityWithIntent the Activity starts without any problems but It is using my Real Application class instead of the Mocked Application class. Any ideas how I can fix that or how I can execute code after onCreate of the application was called but before onCreate of my Activity get's called within my instrument test?

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


回答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.



回答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.



回答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.



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

}