• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.robolectric.shadows;
2 
3 import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
4 import static android.os.Build.VERSION_CODES.KITKAT;
5 import static android.os.Build.VERSION_CODES.LOLLIPOP;
6 import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1;
7 import static android.os.Build.VERSION_CODES.M;
8 import static android.os.Build.VERSION_CODES.O;
9 import static com.google.common.truth.Truth.assertThat;
10 import static org.junit.Assert.assertFalse;
11 import static org.junit.Assert.assertNull;
12 import static org.junit.Assert.assertSame;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.robolectric.Shadows.shadowOf;
16 
17 import android.app.Activity;
18 import android.app.Application;
19 import android.content.ActivityNotFoundException;
20 import android.content.BroadcastReceiver;
21 import android.content.ComponentName;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.content.IntentFilter;
25 import android.content.RestrictionsManager;
26 import android.content.ServiceConnection;
27 import android.hardware.SystemSensorManager;
28 import android.hardware.fingerprint.FingerprintManager;
29 import android.media.session.MediaSessionManager;
30 import android.net.nsd.NsdManager;
31 import android.os.BatteryManager;
32 import android.os.Binder;
33 import android.os.IBinder;
34 import android.os.UserManager;
35 import android.os.Vibrator;
36 import android.print.PrintManager;
37 import android.telephony.SubscriptionManager;
38 import android.view.Gravity;
39 import android.view.LayoutInflater;
40 import android.view.accessibility.AccessibilityManager;
41 import android.view.accessibility.CaptioningManager;
42 import android.view.autofill.AutofillManager;
43 import android.view.textclassifier.TextClassificationManager;
44 import android.widget.LinearLayout;
45 import android.widget.PopupWindow;
46 import androidx.test.core.app.ApplicationProvider;
47 import androidx.test.ext.junit.runners.AndroidJUnit4;
48 import java.util.List;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.robolectric.Robolectric;
53 import org.robolectric.RuntimeEnvironment;
54 import org.robolectric.Shadows;
55 import org.robolectric.annotation.Config;
56 import org.robolectric.util.Scheduler;
57 
58 @RunWith(AndroidJUnit4.class)
59 public class ShadowApplicationTest {
60 
61   private Application context;
62 
63   @Before
setUp()64   public void setUp() {
65     context = ApplicationProvider.getApplicationContext();
66   }
67 
68   @Test
shouldBeAContext()69   public void shouldBeAContext() throws Exception {
70     assertThat(Robolectric.setupActivity(Activity.class).getApplication())
71         .isSameAs(ApplicationProvider.getApplicationContext());
72     assertThat(Robolectric.setupActivity(Activity.class).getApplication().getApplicationContext())
73         .isSameAs(ApplicationProvider.getApplicationContext());
74   }
75 
76   @Test
shouldProvideServices()77   public void shouldProvideServices() throws Exception {
78     assertThat(context.getSystemService(Context.ACTIVITY_SERVICE))
79         .isInstanceOf(android.app.ActivityManager.class);
80     assertThat(context.getSystemService(Context.POWER_SERVICE))
81         .isInstanceOf(android.os.PowerManager.class);
82     assertThat(context.getSystemService(Context.ALARM_SERVICE))
83         .isInstanceOf(android.app.AlarmManager.class);
84     assertThat(context.getSystemService(Context.NOTIFICATION_SERVICE))
85         .isInstanceOf(android.app.NotificationManager.class);
86     assertThat(context.getSystemService(Context.KEYGUARD_SERVICE))
87         .isInstanceOf(android.app.KeyguardManager.class);
88     assertThat(context.getSystemService(Context.LOCATION_SERVICE))
89         .isInstanceOf(android.location.LocationManager.class);
90     assertThat(context.getSystemService(Context.SEARCH_SERVICE))
91         .isInstanceOf(android.app.SearchManager.class);
92     assertThat(context.getSystemService(Context.SENSOR_SERVICE))
93         .isInstanceOf(SystemSensorManager.class);
94     assertThat(context.getSystemService(Context.STORAGE_SERVICE))
95         .isInstanceOf(android.os.storage.StorageManager.class);
96     assertThat(context.getSystemService(Context.VIBRATOR_SERVICE)).isInstanceOf(Vibrator.class);
97     assertThat(context.getSystemService(Context.CONNECTIVITY_SERVICE))
98         .isInstanceOf(android.net.ConnectivityManager.class);
99     assertThat(context.getSystemService(Context.WIFI_SERVICE))
100         .isInstanceOf(android.net.wifi.WifiManager.class);
101     assertThat(context.getSystemService(Context.AUDIO_SERVICE))
102         .isInstanceOf(android.media.AudioManager.class);
103     assertThat(context.getSystemService(Context.TELEPHONY_SERVICE))
104         .isInstanceOf(android.telephony.TelephonyManager.class);
105     assertThat(context.getSystemService(Context.INPUT_METHOD_SERVICE))
106         .isInstanceOf(android.view.inputmethod.InputMethodManager.class);
107     assertThat(context.getSystemService(Context.UI_MODE_SERVICE))
108         .isInstanceOf(android.app.UiModeManager.class);
109     assertThat(context.getSystemService(Context.DOWNLOAD_SERVICE))
110         .isInstanceOf(android.app.DownloadManager.class);
111     assertThat(context.getSystemService(Context.DEVICE_POLICY_SERVICE))
112         .isInstanceOf(android.app.admin.DevicePolicyManager.class);
113     assertThat(context.getSystemService(Context.DROPBOX_SERVICE))
114         .isInstanceOf(android.os.DropBoxManager.class);
115     assertThat(context.getSystemService(Context.MEDIA_ROUTER_SERVICE))
116         .isInstanceOf(android.media.MediaRouter.class);
117     assertThat(context.getSystemService(Context.ACCESSIBILITY_SERVICE))
118         .isInstanceOf(AccessibilityManager.class);
119     assertThat(context.getSystemService(Context.NSD_SERVICE)).isInstanceOf(NsdManager.class);
120   }
121 
122   @Test
123   @Config(minSdk = JELLY_BEAN_MR1)
shouldProvideServicesIntroducedInJellyBeanMr1()124   public void shouldProvideServicesIntroducedInJellyBeanMr1() throws Exception {
125     assertThat(context.getSystemService(Context.DISPLAY_SERVICE))
126         .isInstanceOf(android.hardware.display.DisplayManager.class);
127     assertThat(context.getSystemService(Context.USER_SERVICE)).isInstanceOf(UserManager.class);
128   }
129 
130   @Test
131   @Config(minSdk = KITKAT)
shouldProvideServicesIntroducedInKitKat()132   public void shouldProvideServicesIntroducedInKitKat() throws Exception {
133     assertThat(context.getSystemService(Context.PRINT_SERVICE)).isInstanceOf(PrintManager.class);
134     assertThat(context.getSystemService(Context.CAPTIONING_SERVICE))
135         .isInstanceOf(CaptioningManager.class);
136   }
137 
138   @Test
139   @Config(minSdk = LOLLIPOP)
shouldProvideServicesIntroducedInLollipop()140   public void shouldProvideServicesIntroducedInLollipop() throws Exception {
141     assertThat(context.getSystemService(Context.MEDIA_SESSION_SERVICE))
142         .isInstanceOf(MediaSessionManager.class);
143     assertThat(context.getSystemService(Context.BATTERY_SERVICE))
144         .isInstanceOf(BatteryManager.class);
145     assertThat(context.getSystemService(Context.RESTRICTIONS_SERVICE))
146         .isInstanceOf(RestrictionsManager.class);
147   }
148 
149   @Test
150   @Config(minSdk = LOLLIPOP_MR1)
shouldProvideServicesIntroducedInLollipopMr1()151   public void shouldProvideServicesIntroducedInLollipopMr1() throws Exception {
152     assertThat(context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE))
153         .isInstanceOf(SubscriptionManager.class);
154   }
155 
156   @Test
157   @Config(minSdk = M)
shouldProvideServicesIntroducedMarshmallow()158   public void shouldProvideServicesIntroducedMarshmallow() throws Exception {
159     assertThat(context.getSystemService(Context.FINGERPRINT_SERVICE))
160         .isInstanceOf(FingerprintManager.class);
161   }
162 
163   @Test
164   @Config(minSdk = O)
shouldProvideServicesIntroducedOreo()165   public void shouldProvideServicesIntroducedOreo() throws Exception {
166     // Context.AUTOFILL_MANAGER_SERVICE is marked @hide and this is the documented way to obtain
167     // this service.
168     AutofillManager autofillManager = context.getSystemService(AutofillManager.class);
169     assertThat(autofillManager).isNotNull();
170 
171     assertThat(context.getSystemService(Context.TEXT_CLASSIFICATION_SERVICE))
172         .isInstanceOf(TextClassificationManager.class);
173   }
174 
shouldProvideLayoutInflater()175   @Test public void shouldProvideLayoutInflater() throws Exception {
176     Object systemService = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
177     assertThat(systemService).isInstanceOf(LayoutInflater.class);
178   }
179 
180   @Test
181   @Config(minSdk = KITKAT)
shouldCorrectlyInstantiatedAccessibilityService()182   public void shouldCorrectlyInstantiatedAccessibilityService() throws Exception {
183     AccessibilityManager accessibilityManager =
184         (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
185 
186     AccessibilityManager.TouchExplorationStateChangeListener listener = createTouchListener();
187     assertThat(accessibilityManager.addTouchExplorationStateChangeListener(listener)).isTrue();
188     assertThat(accessibilityManager.removeTouchExplorationStateChangeListener(listener)).isTrue();
189   }
190 
createTouchListener()191   private static AccessibilityManager.TouchExplorationStateChangeListener createTouchListener() {
192     return enabled -> {};
193   }
194 
195   @Test
bindServiceShouldCallOnServiceConnectedWithDefaultValues()196   public void bindServiceShouldCallOnServiceConnectedWithDefaultValues() {
197     TestService service = new TestService();
198     ComponentName expectedComponentName = new ComponentName("", "");
199     Binder expectedBinder = new Binder();
200     Shadows.shadowOf(context)
201         .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder);
202     context.bindService(new Intent(""), service, Context.BIND_AUTO_CREATE);
203     assertThat(service.name).isEqualTo(expectedComponentName);
204     assertThat(service.service).isEqualTo(expectedBinder);
205     assertThat(service.nameUnbound).isNull();
206     context.unbindService(service);
207     assertThat(service.nameUnbound).isEqualTo(expectedComponentName);
208   }
209 
210   @Test
bindServiceShouldCallOnServiceConnectedWithNullValues()211   public void bindServiceShouldCallOnServiceConnectedWithNullValues() {
212     TestService service = new TestService();
213     context.bindService(new Intent(""), service, Context.BIND_AUTO_CREATE);
214     assertThat(service.name).isNull();
215     assertThat(service.service).isNull();
216   }
217 
218   @Test
bindServiceShouldCallOnServiceConnectedWhenNotPaused()219   public void bindServiceShouldCallOnServiceConnectedWhenNotPaused() {
220     ShadowLooper.pauseMainLooper();
221     ComponentName expectedComponentName = new ComponentName("", "");
222     Binder expectedBinder = new Binder();
223     Intent expectedIntent = new Intent("expected");
224     Shadows.shadowOf(context)
225         .setComponentNameAndServiceForBindServiceForIntent(
226             expectedIntent, expectedComponentName, expectedBinder);
227 
228     TestService service = new TestService();
229     assertThat(context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE)).isTrue();
230 
231     assertThat(service.name).isNull();
232     assertThat(service.service).isNull();
233 
234     ShadowLooper.unPauseMainLooper();
235 
236     assertThat(service.name).isEqualTo(expectedComponentName);
237     assertThat(service.service).isEqualTo(expectedBinder);
238   }
239 
240   @Test
unbindServiceShouldCallOnServiceDisconnectedWhenNotPaused()241   public void unbindServiceShouldCallOnServiceDisconnectedWhenNotPaused() {
242     TestService service = new TestService();
243     ComponentName expectedComponentName = new ComponentName("", "");
244     Binder expectedBinder = new Binder();
245     Intent expectedIntent = new Intent("expected");
246     Shadows.shadowOf(context)
247         .setComponentNameAndServiceForBindServiceForIntent(
248             expectedIntent, expectedComponentName, expectedBinder);
249     context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE);
250     ShadowLooper.pauseMainLooper();
251 
252     context.unbindService(service);
253     assertThat(service.nameUnbound).isNull();
254     ShadowLooper.unPauseMainLooper();
255     assertThat(service.nameUnbound).isEqualTo(expectedComponentName);
256   }
257 
258   @Test
unbindServiceAddsEntryToUnboundServicesCollection()259   public void unbindServiceAddsEntryToUnboundServicesCollection() {
260     TestService service = new TestService();
261     ComponentName expectedComponentName = new ComponentName("", "");
262     Binder expectedBinder = new Binder();
263     Intent expectedIntent = new Intent("expected");
264     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
265     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntent, expectedComponentName, expectedBinder);
266     context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE);
267     context.unbindService(service);
268     assertThat(shadowApplication.getUnboundServiceConnections()).hasSize(1);
269     assertThat(shadowApplication.getUnboundServiceConnections().get(0)).isSameAs(service);
270   }
271 
272   @Test
declaringServiceUnbindableMakesBindServiceReturnFalse()273   public void declaringServiceUnbindableMakesBindServiceReturnFalse() {
274     ShadowLooper.pauseMainLooper();
275     TestService service = new TestService();
276     ComponentName expectedComponentName = new ComponentName("", "");
277     Binder expectedBinder = new Binder();
278     Intent expectedIntent = new Intent("refuseToBind");
279     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
280     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntent, expectedComponentName, expectedBinder);
281     shadowApplication.declareActionUnbindable(expectedIntent.getAction());
282     assertFalse(context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE));
283     ShadowLooper.unPauseMainLooper();
284     assertThat(service.name).isNull();
285     assertThat(service.service).isNull();
286     assertThat(shadowApplication.peekNextStartedService()).isNull();
287   }
288 
289   @Test
bindServiceWithMultipleIntentsMapping()290   public void bindServiceWithMultipleIntentsMapping() {
291     TestService service = new TestService();
292     ComponentName expectedComponentNameOne = new ComponentName("package", "one");
293     Binder expectedBinderOne = new Binder();
294     Intent expectedIntentOne = new Intent("expected_one");
295     ComponentName expectedComponentNameTwo = new ComponentName("package", "two");
296     Binder expectedBinderTwo = new Binder();
297     Intent expectedIntentTwo = new Intent("expected_two");
298     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
299     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntentOne, expectedComponentNameOne, expectedBinderOne);
300     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntentTwo, expectedComponentNameTwo, expectedBinderTwo);
301     context.bindService(expectedIntentOne, service, Context.BIND_AUTO_CREATE);
302     assertThat(service.name).isEqualTo(expectedComponentNameOne);
303     assertThat(service.service).isEqualTo(expectedBinderOne);
304     context.bindService(expectedIntentTwo, service, Context.BIND_AUTO_CREATE);
305     assertThat(service.name).isEqualTo(expectedComponentNameTwo);
306     assertThat(service.service).isEqualTo(expectedBinderTwo);
307   }
308 
309   @Test
bindServiceWithMultipleIntentsMappingWithDefault()310   public void bindServiceWithMultipleIntentsMappingWithDefault() {
311     TestService service = new TestService();
312     ComponentName expectedComponentNameOne = new ComponentName("package", "one");
313     Binder expectedBinderOne = new Binder();
314     Intent expectedIntentOne = new Intent("expected_one");
315     ComponentName expectedComponentNameTwo = new ComponentName("package", "two");
316     Binder expectedBinderTwo = new Binder();
317     Intent expectedIntentTwo = new Intent("expected_two");
318     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
319     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntentOne, expectedComponentNameOne, expectedBinderOne);
320     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntentTwo, expectedComponentNameTwo, expectedBinderTwo);
321     context.bindService(expectedIntentOne, service, Context.BIND_AUTO_CREATE);
322     assertThat(service.name).isEqualTo(expectedComponentNameOne);
323     assertThat(service.service).isEqualTo(expectedBinderOne);
324     context.bindService(expectedIntentTwo, service, Context.BIND_AUTO_CREATE);
325     assertThat(service.name).isEqualTo(expectedComponentNameTwo);
326     assertThat(service.service).isEqualTo(expectedBinderTwo);
327     context.bindService(new Intent("unknown"), service, Context.BIND_AUTO_CREATE);
328     assertThat(service.name).isNull();
329     assertThat(service.service).isNull();
330   }
331 
332   @Test
unbindServiceWithMultipleIntentsMapping()333   public void unbindServiceWithMultipleIntentsMapping() {
334     TestService serviceOne = new TestService();
335     ComponentName expectedComponentNameOne = new ComponentName("package", "one");
336     Binder expectedBinderOne = new Binder();
337     Intent expectedIntentOne = new Intent("expected_one");
338     TestService serviceTwo = new TestService();
339     ComponentName expectedComponentNameTwo = new ComponentName("package", "two");
340     Binder expectedBinderTwo = new Binder();
341     Intent expectedIntentTwo = new Intent("expected_two");
342     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
343     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntentOne, expectedComponentNameOne, expectedBinderOne);
344     shadowApplication.setComponentNameAndServiceForBindServiceForIntent(expectedIntentTwo, expectedComponentNameTwo, expectedBinderTwo);
345 
346     context.bindService(expectedIntentOne, serviceOne, Context.BIND_AUTO_CREATE);
347     assertThat(serviceOne.nameUnbound).isNull();
348     context.unbindService(serviceOne);
349     assertThat(serviceOne.name).isEqualTo(expectedComponentNameOne);
350 
351     context.bindService(expectedIntentTwo, serviceTwo, Context.BIND_AUTO_CREATE);
352     assertThat(serviceTwo.nameUnbound).isNull();
353     context.unbindService(serviceTwo);
354     assertThat(serviceTwo.name).isEqualTo(expectedComponentNameTwo);
355 
356     TestService serviceDefault = new TestService();
357     context.bindService(new Intent("default"), serviceDefault, Context.BIND_AUTO_CREATE);
358     assertThat(serviceDefault.nameUnbound).isNull();
359     context.unbindService(serviceDefault);
360     assertThat(serviceDefault.name).isNull();
361   }
362 
363   @Test
shouldHaveStoppedServiceIntentAndIndicateServiceWasntRunning()364   public void shouldHaveStoppedServiceIntentAndIndicateServiceWasntRunning() {
365     ShadowApplication shadowApplication = Shadows.shadowOf(context);
366 
367     Activity activity = Robolectric.setupActivity(Activity.class);
368 
369     Intent intent = getSomeActionIntent("some.action");
370 
371     boolean wasRunning = activity.stopService(intent);
372 
373     assertFalse(wasRunning);
374     assertThat(shadowApplication.getNextStoppedService()).isEqualTo(intent);
375   }
376 
getSomeActionIntent(String action)377   private Intent getSomeActionIntent(String action) {
378     Intent intent = new Intent();
379     intent.setAction(action);
380     return intent;
381   }
382 
383   @Test
shouldHaveStoppedServiceIntentAndIndicateServiceWasRunning()384   public void shouldHaveStoppedServiceIntentAndIndicateServiceWasRunning() {
385     ShadowApplication shadowApplication = shadowOf(context);
386 
387     Activity activity = Robolectric.setupActivity(Activity.class);
388 
389     Intent intent = getSomeActionIntent("some.action");
390 
391     activity.startService(intent);
392 
393     boolean wasRunning = activity.stopService(intent);
394 
395     assertTrue(wasRunning);
396     assertThat(shadowApplication.getNextStoppedService()).isEqualTo(intent);
397   }
398 
399   @Test
shouldHaveStoppedServiceByStartedComponent()400   public void shouldHaveStoppedServiceByStartedComponent() {
401     ShadowApplication shadowApplication = shadowOf(context);
402 
403     Activity activity = Robolectric.setupActivity(Activity.class);
404 
405     ComponentName componentName = new ComponentName("package.test", "package.test.TestClass");
406     Intent startServiceIntent = new Intent().setComponent(componentName);
407 
408     ComponentName startedComponent = activity.startService(startServiceIntent);
409     assertThat(startedComponent.getPackageName()).isEqualTo("package.test");
410     assertThat(startedComponent.getClassName()).isEqualTo("package.test.TestClass");
411 
412     Intent stopServiceIntent = new Intent().setComponent(startedComponent);
413     stopServiceIntent.putExtra("someExtra", "someValue");
414     boolean wasRunning = activity.stopService(stopServiceIntent);
415 
416     assertTrue(wasRunning);
417     final Intent nextStoppedService = shadowApplication.getNextStoppedService();
418     assertThat(nextStoppedService.filterEquals(startServiceIntent)).isTrue();
419     assertThat(nextStoppedService.getStringExtra("someExtra")).isEqualTo("someValue");
420   }
421 
422   @Test
shouldClearStartedServiceIntents()423   public void shouldClearStartedServiceIntents() {
424     context.startService(getSomeActionIntent("some.action"));
425     context.startService(getSomeActionIntent("another.action"));
426 
427     shadowOf(context).clearStartedServices();
428 
429     assertNull(shadowOf(context).getNextStartedService());
430   }
431 
432   @Test
shouldThrowIfContainsRegisteredReceiverOfAction()433   public void shouldThrowIfContainsRegisteredReceiverOfAction() {
434     Activity activity = Robolectric.setupActivity(Activity.class);
435     activity.registerReceiver(new TestBroadcastReceiver(), new IntentFilter("Foo"));
436 
437     try {
438       shadowOf(context).assertNoBroadcastListenersOfActionRegistered(activity, "Foo");
439 
440       fail("should have thrown IllegalStateException");
441     } catch (IllegalStateException e) {
442       // ok
443     }
444   }
445 
446   @Test
shouldNotThrowIfDoesNotContainsRegisteredReceiverOfAction()447   public void shouldNotThrowIfDoesNotContainsRegisteredReceiverOfAction() {
448     Activity activity = Robolectric.setupActivity(Activity.class);
449     activity.registerReceiver(new TestBroadcastReceiver(), new IntentFilter("Foo"));
450 
451     shadowOf(context).assertNoBroadcastListenersOfActionRegistered(activity, "Bar");
452   }
453 
454   @Test
canAnswerIfReceiverIsRegisteredForIntent()455   public void canAnswerIfReceiverIsRegisteredForIntent() throws Exception {
456     BroadcastReceiver expectedReceiver = new TestBroadcastReceiver();
457     ShadowApplication shadowApplication = shadowOf(context);
458     assertFalse(shadowApplication.hasReceiverForIntent(new Intent("Foo")));
459     context.registerReceiver(expectedReceiver, new IntentFilter("Foo"));
460 
461     assertTrue(shadowApplication.hasReceiverForIntent(new Intent("Foo")));
462   }
463 
464   @Test
canFindAllReceiversForAnIntent()465   public void canFindAllReceiversForAnIntent() throws Exception {
466     BroadcastReceiver expectedReceiver = new TestBroadcastReceiver();
467     ShadowApplication shadowApplication = shadowOf(context);
468     assertFalse(shadowApplication.hasReceiverForIntent(new Intent("Foo")));
469     context.registerReceiver(expectedReceiver, new IntentFilter("Foo"));
470     context.registerReceiver(expectedReceiver, new IntentFilter("Foo"));
471 
472     assertThat(shadowApplication.getReceiversForIntent(new Intent("Foo"))).hasSize(2);
473   }
474 
475   @Test
broadcasts_shouldBeLogged()476   public void broadcasts_shouldBeLogged() {
477     Intent broadcastIntent = new Intent("foo");
478     context.sendBroadcast(broadcastIntent);
479 
480     List<Intent> broadcastIntents = shadowOf(context).getBroadcastIntents();
481     assertThat(broadcastIntents).hasSize(1);
482     assertThat(broadcastIntents.get(0)).isEqualTo(broadcastIntent);
483   }
484 
485   @Test
sendStickyBroadcast()486   public void sendStickyBroadcast() {
487     Intent broadcastIntent = new Intent("Foo");
488     context.sendStickyBroadcast(broadcastIntent);
489 
490     // Register after the broadcast has fired. We should immediately get a sticky event.
491     TestBroadcastReceiver receiver = new TestBroadcastReceiver();
492     context.registerReceiver(receiver, new IntentFilter("Foo"));
493     assertTrue(receiver.isSticky);
494 
495     // Fire the broadcast again, and we should get a non-sticky event.
496     context.sendStickyBroadcast(broadcastIntent);
497     assertFalse(receiver.isSticky);
498   }
499 
500   @Test
shouldRememberResourcesAfterLazilyLoading()501   public void shouldRememberResourcesAfterLazilyLoading() throws Exception {
502     assertSame(context.getResources(), context.getResources());
503   }
504 
505   @Test
startActivity_whenActivityCheckingEnabled_checksPackageManagerResolveInfo()506   public void startActivity_whenActivityCheckingEnabled_checksPackageManagerResolveInfo() throws Exception {
507     shadowOf(context).checkActivities(true);
508 
509     String action = "com.does.not.exist.android.app.v2.mobile";
510 
511     try {
512       context.startActivity(new Intent(action).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
513       fail("Expected startActivity to throw ActivityNotFoundException!");
514     } catch (ActivityNotFoundException e) {
515       assertThat(e.getMessage()).contains(action);
516       assertThat(shadowOf(context).getNextStartedActivity()).isNull();
517     }
518   }
519 
520   @Test
bindServiceShouldAddServiceConnectionToListOfBoundServiceConnections()521   public void bindServiceShouldAddServiceConnectionToListOfBoundServiceConnections() {
522     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
523     final ServiceConnection expectedServiceConnection = new EmptyServiceConnection();
524 
525     assertThat(shadowApplication.getBoundServiceConnections()).hasSize(0);
526     assertThat(context.bindService(new Intent("connect"), expectedServiceConnection, 0)).isTrue();
527     assertThat(shadowApplication.getBoundServiceConnections()).hasSize(1);
528     assertThat(shadowApplication.getBoundServiceConnections().get(0))
529         .isSameAs(expectedServiceConnection);
530   }
531 
532   @Test
bindServiceShouldAddServiceConnectionToListOfBoundServiceConnectionsEvenIfServiceUnboundable()533   public void bindServiceShouldAddServiceConnectionToListOfBoundServiceConnectionsEvenIfServiceUnboundable() {
534     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
535     final ServiceConnection expectedServiceConnection = new EmptyServiceConnection();
536     final String unboundableAction = "refuse";
537     final Intent serviceIntent = new Intent(unboundableAction);
538     shadowApplication.declareActionUnbindable(unboundableAction);
539     assertThat(shadowApplication.getBoundServiceConnections()).hasSize(0);
540     assertThat(context.bindService(serviceIntent, expectedServiceConnection, 0)).isFalse();
541     assertThat(shadowApplication.getBoundServiceConnections()).hasSize(1);
542     assertThat(shadowApplication.getBoundServiceConnections().get(0)).isSameAs(expectedServiceConnection);
543   }
544 
545   @Test
unbindServiceShouldRemoveServiceConnectionFromListOfBoundServiceConnections()546   public void unbindServiceShouldRemoveServiceConnectionFromListOfBoundServiceConnections() {
547     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
548     final ServiceConnection expectedServiceConnection = new EmptyServiceConnection();
549 
550     assertThat(context.bindService(new Intent("connect"), expectedServiceConnection, 0)).isTrue();
551     assertThat(shadowApplication.getBoundServiceConnections()).hasSize(1);
552     assertThat(shadowApplication.getUnboundServiceConnections()).hasSize(0);
553     context.unbindService(expectedServiceConnection);
554     assertThat(shadowApplication.getBoundServiceConnections()).hasSize(0);
555     assertThat(shadowApplication.getUnboundServiceConnections()).hasSize(1);
556     assertThat(shadowApplication.getUnboundServiceConnections().get(0))
557         .isSameAs(expectedServiceConnection);
558   }
559 
560   @Test
getThreadScheduler_shouldMatchRobolectricValue()561   public void getThreadScheduler_shouldMatchRobolectricValue() {
562     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
563     assertThat(shadowApplication.getForegroundThreadScheduler()).isSameAs(Robolectric.getForegroundThreadScheduler());
564     assertThat(shadowApplication.getBackgroundThreadScheduler()).isSameAs(Robolectric.getBackgroundThreadScheduler());
565   }
566 
567   @Test
getForegroundThreadScheduler_shouldMatchRuntimeEnvironment()568   public void getForegroundThreadScheduler_shouldMatchRuntimeEnvironment() {
569     Scheduler s = new Scheduler();
570     RuntimeEnvironment.setMasterScheduler(s);
571     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
572     assertThat(shadowApplication.getForegroundThreadScheduler()).isSameAs(s);
573   }
574 
575   @Test
getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_byDefault()576   public void getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_byDefault() {
577     Scheduler s = new Scheduler();
578     RuntimeEnvironment.setMasterScheduler(s);
579     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
580     assertThat(shadowApplication.getBackgroundThreadScheduler()).isNotSameAs(RuntimeEnvironment.getMasterScheduler());
581   }
582 
583   @Test
getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_withAdvancedScheduling()584   public void getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_withAdvancedScheduling() {
585     Scheduler s = new Scheduler();
586     RuntimeEnvironment.setMasterScheduler(s);
587     final ShadowApplication shadowApplication = Shadows.shadowOf(context);
588     assertThat(shadowApplication.getBackgroundThreadScheduler()).isNotSameAs(s);
589   }
590 
591   @Test
getLatestPopupWindow()592   public void getLatestPopupWindow() {
593     PopupWindow pw = new PopupWindow(new LinearLayout(context));
594 
595     pw.showAtLocation(new LinearLayout(context), Gravity.CENTER, 0, 0);
596 
597     PopupWindow latestPopupWindow = ShadowApplication.getInstance().getLatestPopupWindow();
598     assertThat(latestPopupWindow).isSameAs(pw);
599   }
600 
601   /////////////////////////////
602 
603   private static class EmptyServiceConnection implements ServiceConnection {
604     @Override
onServiceConnected(ComponentName name, IBinder service)605     public void onServiceConnected(ComponentName name, IBinder service) {}
606 
607     @Override
onServiceDisconnected(ComponentName name)608     public void onServiceDisconnected(ComponentName name) {}
609   }
610 
611   public static class TestBroadcastReceiver extends BroadcastReceiver {
612     public Context context;
613     public Intent intent;
614     public boolean isSticky;
615 
616     @Override
onReceive(Context context, Intent intent)617     public void onReceive(Context context, Intent intent) {
618       this.context = context;
619       this.intent = intent;
620       this.isSticky = isInitialStickyBroadcast();
621     }
622   }
623 }
624