简体   繁体   中英

You need to use a Theme.AppCompat theme --> in Unit Test

I know this topic has been discussed but it is a little different here:

  • App works fine
  • Error is displayed only in unit test
  • Theme is Fine (new created sample project)

How to reproduce:

  1. Create just a new project --> FullScreenActivity Android 4.3
  2. Create a unit test
  3. Run it

    public class FullscreenActivityTest extends ActivityUnitTestCase<FullscreenActivity> { public FullscreenActivityTest() { super(FullscreenActivity.class); } public void testStart() { startActivity(new Intent(getInstrumentation().getTargetContext(), FullscreenActivity.class), null, null); Assert.assertNotNull(getActivity()); }

    }

Tested with:

  1. Nexus 5 Emulator
  2. Nexus 6P Emulator

Each time the same, app works fine. Unit test fails with:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
        at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:124)
        at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
        at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59)
        at com.sample.foobar.FullscreenActivity.onCreate(FullscreenActivity.java:88)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.test.ActivityUnitTestCase.startActivity(ActivityUnitTestCase.java:163)

Thanks,

Paul

The following code worked for me -- added to the unit test:

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

See also: ActivityUnitTestCase and startActivity with ActionBarActivity

Also possible

Use ActivityInstrumentationTestCase2 instead of ActivityUnitTestCase fixes the issue too.

In addition the "onPause" of the activity isn't called. Which is somehow odd with ActivityUnitTestCase

Using the new AndroidX libraries this can be solved by passing the theme to the fragment launching method:

val authDialogScenario = launchFragment<AuthDialog>(themeResId = R.style.AppTheme)

This was the solution in my case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM