简体   繁体   中英

Inject a Mock context in ActivityUnitTestCase Fails

Base from the document in ActivityUnitTestCase

void setActivityContext (Context activityContext)

If you wish to inject a Mock, Isolated, or otherwise altered context, you can do so here. You must call this function before calling startActivity(Intent, Bundle, Object). If you wish to obtain a real Context, as a building block, use getInstrumentation().getTargetContext().

but when i use it as shown below

ContextWrapper context = mock(ContextWrapper.class);
Resources resources = mock(Resources.class);
LayoutInflater layoutInflater = mock(LayoutInflater.class);

when(context.getPackageName()).thenReturn("package_name");
when(context.getResources()).thenReturn(resources);
when(context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).thenReturn(layoutInflater);
        setActivityContext(context);

Intent intent = new Intent(getInstrumentation().getTargetContext(), MyActivity.class);
startActivity(intent, null, null);

it fails with these error, i can't seem to find what i miss, i mock a context because i need to stub some method in context

java.lang.AssertionError: LayoutInflater not found.
at android.view.LayoutInflater.from(LayoutInflater.java:231)
at com.android.internal.policy.PhoneWindow.<init>(PhoneWindow.java:306)
at android.app.Activity.attach(Activity.java:6179)
at android.app.Instrumentation.newActivity(Instrumentation.java:1044)
at android.support.test.runner.MonitoringInstrumentation.newActivity(MonitoringInstrumentation.java:601)
at android.test.ActivityUnitTestCase.startActivity(ActivityUnitTestCase.java:147)

Class ActivityUnitTestCase is deprecated now in API level 24. Write Local Unit Tests instead.

Please check : https://developer.android.com/reference/android/test/ActivityUnitTestCase.html#setActivityContext(android.content.Context)

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