1 package org.robolectric.shadows; 2 3 import static android.os.Build.VERSION_CODES.LOLLIPOP_MR1; 4 import static android.os.Build.VERSION_CODES.M; 5 import static android.os.Build.VERSION_CODES.O; 6 import static com.google.common.truth.Truth.assertThat; 7 import static java.util.concurrent.TimeUnit.MILLISECONDS; 8 import static org.junit.Assert.assertFalse; 9 import static org.junit.Assert.assertNotNull; 10 import static org.junit.Assert.assertNull; 11 import static org.junit.Assert.assertSame; 12 import static org.junit.Assert.assertTrue; 13 import static org.junit.Assert.fail; 14 import static org.robolectric.Shadows.shadowOf; 15 import static org.robolectric.annotation.LooperMode.Mode.LEGACY; 16 import static org.robolectric.shadows.ShadowLooper.shadowMainLooper; 17 18 import android.app.Activity; 19 import android.app.Application; 20 import android.content.ActivityNotFoundException; 21 import android.content.BroadcastReceiver; 22 import android.content.ComponentName; 23 import android.content.Context; 24 import android.content.Intent; 25 import android.content.IntentFilter; 26 import android.content.RestrictionsManager; 27 import android.content.ServiceConnection; 28 import android.hardware.SystemSensorManager; 29 import android.hardware.fingerprint.FingerprintManager; 30 import android.media.session.MediaSessionManager; 31 import android.net.nsd.NsdManager; 32 import android.os.BatteryManager; 33 import android.os.Binder; 34 import android.os.Build.VERSION_CODES; 35 import android.os.IBinder; 36 import android.os.UserManager; 37 import android.os.Vibrator; 38 import android.print.PrintManager; 39 import android.telephony.SubscriptionManager; 40 import android.view.Gravity; 41 import android.view.LayoutInflater; 42 import android.view.accessibility.AccessibilityManager; 43 import android.view.accessibility.CaptioningManager; 44 import android.view.autofill.AutofillManager; 45 import android.view.textclassifier.TextClassificationManager; 46 import android.widget.LinearLayout; 47 import android.widget.PopupWindow; 48 import androidx.test.core.app.ApplicationProvider; 49 import androidx.test.ext.junit.runners.AndroidJUnit4; 50 import java.util.List; 51 import java.util.concurrent.CountDownLatch; 52 import org.junit.Before; 53 import org.junit.Test; 54 import org.junit.runner.RunWith; 55 import org.robolectric.Robolectric; 56 import org.robolectric.RuntimeEnvironment; 57 import org.robolectric.Shadows; 58 import org.robolectric.annotation.Config; 59 import org.robolectric.annotation.LooperMode; 60 import org.robolectric.shadows.testing.TestActivity; 61 import org.robolectric.util.Scheduler; 62 63 @RunWith(AndroidJUnit4.class) 64 public class ShadowApplicationTest { 65 66 private Application context; 67 68 @Before setUp()69 public void setUp() { 70 context = ApplicationProvider.getApplicationContext(); 71 } 72 73 @Test shouldBeAContext()74 public void shouldBeAContext() throws Exception { 75 assertThat(Robolectric.setupActivity(Activity.class).getApplication()) 76 .isSameInstanceAs(ApplicationProvider.getApplicationContext()); 77 assertThat(Robolectric.setupActivity(Activity.class).getApplication().getApplicationContext()) 78 .isSameInstanceAs(ApplicationProvider.getApplicationContext()); 79 } 80 81 @Test shouldProvideServices()82 public void shouldProvideServices() throws Exception { 83 assertThat(context.getSystemService(Context.ACTIVITY_SERVICE)) 84 .isInstanceOf(android.app.ActivityManager.class); 85 assertThat(context.getSystemService(Context.POWER_SERVICE)) 86 .isInstanceOf(android.os.PowerManager.class); 87 assertThat(context.getSystemService(Context.ALARM_SERVICE)) 88 .isInstanceOf(android.app.AlarmManager.class); 89 assertThat(context.getSystemService(Context.NOTIFICATION_SERVICE)) 90 .isInstanceOf(android.app.NotificationManager.class); 91 assertThat(context.getSystemService(Context.KEYGUARD_SERVICE)) 92 .isInstanceOf(android.app.KeyguardManager.class); 93 assertThat(context.getSystemService(Context.LOCATION_SERVICE)) 94 .isInstanceOf(android.location.LocationManager.class); 95 assertThat(context.getSystemService(Context.SEARCH_SERVICE)) 96 .isInstanceOf(android.app.SearchManager.class); 97 assertThat(context.getSystemService(Context.SENSOR_SERVICE)) 98 .isInstanceOf(SystemSensorManager.class); 99 assertThat(context.getSystemService(Context.STORAGE_SERVICE)) 100 .isInstanceOf(android.os.storage.StorageManager.class); 101 assertThat(context.getSystemService(Context.VIBRATOR_SERVICE)).isInstanceOf(Vibrator.class); 102 assertThat(context.getSystemService(Context.CONNECTIVITY_SERVICE)) 103 .isInstanceOf(android.net.ConnectivityManager.class); 104 assertThat(context.getSystemService(Context.WIFI_SERVICE)) 105 .isInstanceOf(android.net.wifi.WifiManager.class); 106 assertThat(context.getSystemService(Context.AUDIO_SERVICE)) 107 .isInstanceOf(android.media.AudioManager.class); 108 assertThat(context.getSystemService(Context.TELEPHONY_SERVICE)) 109 .isInstanceOf(android.telephony.TelephonyManager.class); 110 assertThat(context.getSystemService(Context.INPUT_METHOD_SERVICE)) 111 .isInstanceOf(android.view.inputmethod.InputMethodManager.class); 112 assertThat(context.getSystemService(Context.UI_MODE_SERVICE)) 113 .isInstanceOf(android.app.UiModeManager.class); 114 assertThat(context.getSystemService(Context.DOWNLOAD_SERVICE)) 115 .isInstanceOf(android.app.DownloadManager.class); 116 assertThat(context.getSystemService(Context.DEVICE_POLICY_SERVICE)) 117 .isInstanceOf(android.app.admin.DevicePolicyManager.class); 118 assertThat(context.getSystemService(Context.DROPBOX_SERVICE)) 119 .isInstanceOf(android.os.DropBoxManager.class); 120 assertThat(context.getSystemService(Context.MEDIA_ROUTER_SERVICE)) 121 .isInstanceOf(android.media.MediaRouter.class); 122 assertThat(context.getSystemService(Context.ACCESSIBILITY_SERVICE)) 123 .isInstanceOf(AccessibilityManager.class); 124 assertThat(context.getSystemService(Context.NSD_SERVICE)).isInstanceOf(NsdManager.class); 125 } 126 127 @Test shouldProvideServicesAvailableInAllSdKs()128 public void shouldProvideServicesAvailableInAllSdKs() throws Exception { 129 assertThat(context.getSystemService(Context.DISPLAY_SERVICE)) 130 .isInstanceOf(android.hardware.display.DisplayManager.class); 131 assertThat(context.getSystemService(Context.USER_SERVICE)).isInstanceOf(UserManager.class); 132 assertThat(context.getSystemService(Context.MEDIA_SESSION_SERVICE)) 133 .isInstanceOf(MediaSessionManager.class); 134 assertThat(context.getSystemService(Context.BATTERY_SERVICE)) 135 .isInstanceOf(BatteryManager.class); 136 assertThat(context.getSystemService(Context.RESTRICTIONS_SERVICE)) 137 .isInstanceOf(RestrictionsManager.class); 138 assertThat(context.getSystemService(Context.PRINT_SERVICE)).isInstanceOf(PrintManager.class); 139 assertThat(context.getSystemService(Context.CAPTIONING_SERVICE)) 140 .isInstanceOf(CaptioningManager.class); 141 } 142 143 @Test 144 @Config(minSdk = LOLLIPOP_MR1) shouldProvideServicesIntroducedInLollipopMr1()145 public void shouldProvideServicesIntroducedInLollipopMr1() throws Exception { 146 assertThat(context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE)) 147 .isInstanceOf(SubscriptionManager.class); 148 } 149 150 @Test 151 @Config(minSdk = M) shouldProvideServicesIntroducedMarshmallow()152 public void shouldProvideServicesIntroducedMarshmallow() throws Exception { 153 assertThat(context.getSystemService(Context.FINGERPRINT_SERVICE)) 154 .isInstanceOf(FingerprintManager.class); 155 } 156 157 @Test 158 @Config(minSdk = O) shouldProvideServicesIntroducedOreo()159 public void shouldProvideServicesIntroducedOreo() throws Exception { 160 // Context.AUTOFILL_MANAGER_SERVICE is marked @hide and this is the documented way to obtain 161 // this service. 162 AutofillManager autofillManager = context.getSystemService(AutofillManager.class); 163 assertThat(autofillManager).isNotNull(); 164 165 assertThat(context.getSystemService(Context.TEXT_CLASSIFICATION_SERVICE)) 166 .isInstanceOf(TextClassificationManager.class); 167 } 168 169 @Test shouldProvideLayoutInflater()170 public void shouldProvideLayoutInflater() throws Exception { 171 Object systemService = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 172 assertThat(systemService).isInstanceOf(LayoutInflater.class); 173 } 174 175 @Test shouldCorrectlyInstantiatedAccessibilityService()176 public void shouldCorrectlyInstantiatedAccessibilityService() throws Exception { 177 AccessibilityManager accessibilityManager = 178 (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); 179 180 AccessibilityManager.TouchExplorationStateChangeListener listener = enabled -> {}; 181 assertThat(accessibilityManager.addTouchExplorationStateChangeListener(listener)).isTrue(); 182 assertThat(accessibilityManager.removeTouchExplorationStateChangeListener(listener)).isTrue(); 183 } 184 185 @Test bindServiceShouldThrowIfSetToThrow()186 public void bindServiceShouldThrowIfSetToThrow() { 187 TestService service = new TestService(); 188 ComponentName expectedComponentName = new ComponentName("", ""); 189 Binder expectedBinder = new Binder(); 190 Shadows.shadowOf(context) 191 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 192 SecurityException expectedException = new SecurityException("expected"); 193 Shadows.shadowOf(context).setThrowInBindService(expectedException); 194 195 try { 196 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 197 fail("bindService should throw SecurityException!"); 198 } catch (SecurityException thrownException) { 199 assertThat(thrownException).isEqualTo(expectedException); 200 } 201 } 202 203 @Test 204 public void setBindServiceCallsOnServiceConnectedDirectly_setToTrue_onServiceConnectedCalledDuringCall()205 setBindServiceCallsOnServiceConnectedDirectly_setToTrue_onServiceConnectedCalledDuringCall() { 206 TestService service = new TestService(); 207 ComponentName expectedComponentName = new ComponentName("", ""); 208 Binder expectedBinder = new Binder(); 209 Shadows.shadowOf(context) 210 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 211 Shadows.shadowOf(context).setBindServiceCallsOnServiceConnectedDirectly(true); 212 213 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 214 215 assertThat(service.service).isNotNull(); 216 } 217 218 @Test 219 public void setBindServiceCallsOnServiceConnectedDirectly_setToTrue_locksUntilBound_onServiceConnectedCalledDuringCall()220 setBindServiceCallsOnServiceConnectedDirectly_setToTrue_locksUntilBound_onServiceConnectedCalledDuringCall() 221 throws InterruptedException { 222 final CountDownLatch latch = new CountDownLatch(1); 223 TestService service = 224 new TestService() { 225 @Override 226 public void onServiceConnected(ComponentName name, IBinder service) { 227 super.onServiceConnected(name, service); 228 latch.countDown(); 229 } 230 }; 231 ComponentName expectedComponentName = new ComponentName("", ""); 232 Binder expectedBinder = new Binder(); 233 Shadows.shadowOf(context) 234 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 235 Shadows.shadowOf(context).setBindServiceCallsOnServiceConnectedDirectly(true); 236 237 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 238 239 // Lock waiting for onService connected to finish 240 assertThat(latch.await(1000, MILLISECONDS)).isTrue(); 241 assertThat(service.service).isNotNull(); 242 } 243 244 @Test 245 public void setBindServiceCallsOnServiceConnectedDirectly_setToFalse_onServiceConnectedNotCalledDuringCall()246 setBindServiceCallsOnServiceConnectedDirectly_setToFalse_onServiceConnectedNotCalledDuringCall() { 247 TestService service = new TestService(); 248 ComponentName expectedComponentName = new ComponentName("", ""); 249 Binder expectedBinder = new Binder(); 250 Shadows.shadowOf(context) 251 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 252 Shadows.shadowOf(context).setBindServiceCallsOnServiceConnectedDirectly(false); 253 254 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 255 256 assertThat(service.service).isNull(); 257 } 258 259 @Test 260 public void setBindServiceCallsOnServiceConnectedDirectly_setToFalse_locksUntilBound_onServiceConnectedCalledDuringCall()261 setBindServiceCallsOnServiceConnectedDirectly_setToFalse_locksUntilBound_onServiceConnectedCalledDuringCall() 262 throws InterruptedException { 263 final CountDownLatch latch = new CountDownLatch(1); 264 TestService service = 265 new TestService() { 266 @Override 267 public void onServiceConnected(ComponentName name, IBinder service) { 268 super.onServiceConnected(name, service); 269 latch.countDown(); 270 } 271 }; 272 ComponentName expectedComponentName = new ComponentName("", ""); 273 Binder expectedBinder = new Binder(); 274 Shadows.shadowOf(context) 275 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 276 Shadows.shadowOf(context).setBindServiceCallsOnServiceConnectedDirectly(false); 277 278 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 279 280 // Lock waiting for onService connected to finish 281 assertThat(latch.await(1000, MILLISECONDS)).isFalse(); 282 assertThat(service.service).isNull(); 283 284 // After idling the callback has been made. 285 ShadowLooper.idleMainLooper(); 286 287 assertThat(latch.await(1000, MILLISECONDS)).isTrue(); 288 assertThat(service.service).isNotNull(); 289 } 290 291 @Test 292 public void setBindServiceCallsOnServiceConnectedDirectly_notSet_onServiceConnectedNotCalledDuringCall()293 setBindServiceCallsOnServiceConnectedDirectly_notSet_onServiceConnectedNotCalledDuringCall() { 294 TestService service = new TestService(); 295 ComponentName expectedComponentName = new ComponentName("", ""); 296 Binder expectedBinder = new Binder(); 297 Shadows.shadowOf(context) 298 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 299 300 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 301 302 assertThat(service.service).isNull(); 303 } 304 305 @Test bindServiceShouldCallOnServiceConnectedWithDefaultValues_ifFlagUnset()306 public void bindServiceShouldCallOnServiceConnectedWithDefaultValues_ifFlagUnset() { 307 Shadows.shadowOf(context).setUnbindServiceCallsOnServiceDisconnected(false); 308 TestService service = new TestService(); 309 ComponentName expectedComponentName = new ComponentName("", ""); 310 Binder expectedBinder = new Binder(); 311 Shadows.shadowOf(context) 312 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 313 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 314 shadowMainLooper().idle(); 315 assertThat(service.name).isEqualTo(expectedComponentName); 316 assertThat(service.service).isEqualTo(expectedBinder); 317 assertThat(service.nameDisconnected).isNull(); 318 } 319 320 @Test bindServiceShouldCallOnServiceConnectedWithDefaultValues_ifFlagSet()321 public void bindServiceShouldCallOnServiceConnectedWithDefaultValues_ifFlagSet() { 322 Shadows.shadowOf(context).setUnbindServiceCallsOnServiceDisconnected(true); 323 TestService service = new TestService(); 324 ComponentName expectedComponentName = new ComponentName("", ""); 325 Binder expectedBinder = new Binder(); 326 Shadows.shadowOf(context) 327 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 328 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 329 shadowMainLooper().idle(); 330 assertThat(service.name).isEqualTo(expectedComponentName); 331 assertThat(service.service).isEqualTo(expectedBinder); 332 assertThat(service.nameDisconnected).isNull(); 333 context.unbindService(service); 334 shadowMainLooper().idle(); 335 assertThat(service.nameDisconnected).isEqualTo(expectedComponentName); 336 } 337 338 @Test bindServiceShouldCallOnServiceConnectedWithNullValues()339 public void bindServiceShouldCallOnServiceConnectedWithNullValues() { 340 TestService service = new TestService(); 341 context.bindService(new Intent("").setPackage("package"), service, Context.BIND_AUTO_CREATE); 342 assertThat(service.name).isNull(); 343 assertThat(service.service).isNull(); 344 } 345 346 @Test bindServiceShouldCallOnServiceConnectedWhenNotPaused()347 public void bindServiceShouldCallOnServiceConnectedWhenNotPaused() { 348 shadowMainLooper().pause(); 349 ComponentName expectedComponentName = new ComponentName("", ""); 350 Binder expectedBinder = new Binder(); 351 Intent expectedIntent = new Intent("expected").setPackage("package"); 352 Shadows.shadowOf(context) 353 .setComponentNameAndServiceForBindServiceForIntent( 354 expectedIntent, expectedComponentName, expectedBinder); 355 356 TestService service = new TestService(); 357 assertThat(context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE)).isTrue(); 358 359 assertThat(service.name).isNull(); 360 assertThat(service.service).isNull(); 361 362 shadowMainLooper().idle(); 363 364 assertThat(service.name).isEqualTo(expectedComponentName); 365 assertThat(service.service).isEqualTo(expectedBinder); 366 } 367 368 @Test unbindServiceShouldNotCallOnServiceDisconnected_ifFlagUnset()369 public void unbindServiceShouldNotCallOnServiceDisconnected_ifFlagUnset() { 370 Shadows.shadowOf(context).setUnbindServiceCallsOnServiceDisconnected(false); 371 TestService service = new TestService(); 372 ComponentName expectedComponentName = new ComponentName("", ""); 373 Binder expectedBinder = new Binder(); 374 Intent expectedIntent = new Intent("expected").setPackage("package"); 375 Shadows.shadowOf(context) 376 .setComponentNameAndServiceForBindServiceForIntent( 377 expectedIntent, expectedComponentName, expectedBinder); 378 context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE); 379 380 context.unbindService(service); 381 382 shadowMainLooper().idle(); 383 assertThat(service.name).isEqualTo(expectedComponentName); 384 assertThat(service.service).isEqualTo(expectedBinder); 385 assertThat(service.nameDisconnected).isNull(); 386 } 387 388 @Test unbindServiceShouldCallOnServiceDisconnectedWhenNotPaused_ifFlagSet()389 public void unbindServiceShouldCallOnServiceDisconnectedWhenNotPaused_ifFlagSet() { 390 Shadows.shadowOf(context).setUnbindServiceCallsOnServiceDisconnected(true); 391 TestService service = new TestService(); 392 ComponentName expectedComponentName = new ComponentName("", ""); 393 Binder expectedBinder = new Binder(); 394 Intent expectedIntent = new Intent("expected").setPackage("package"); 395 Shadows.shadowOf(context) 396 .setComponentNameAndServiceForBindServiceForIntent( 397 expectedIntent, expectedComponentName, expectedBinder); 398 context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE); 399 shadowMainLooper().pause(); 400 401 context.unbindService(service); 402 assertThat(service.nameDisconnected).isNull(); 403 shadowMainLooper().idle(); 404 assertThat(service.nameDisconnected).isEqualTo(expectedComponentName); 405 } 406 407 @Test unbindServiceAddsEntryToUnboundServicesCollection()408 public void unbindServiceAddsEntryToUnboundServicesCollection() { 409 TestService service = new TestService(); 410 ComponentName expectedComponentName = new ComponentName("", ""); 411 Binder expectedBinder = new Binder(); 412 Intent expectedIntent = new Intent("expected").setPackage("package"); 413 Shadows.shadowOf(context) 414 .setComponentNameAndServiceForBindServiceForIntent( 415 expectedIntent, expectedComponentName, expectedBinder); 416 context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE); 417 context.unbindService(service); 418 assertThat(Shadows.shadowOf(context).getUnboundServiceConnections()).hasSize(1); 419 assertThat(Shadows.shadowOf(context).getUnboundServiceConnections().get(0)) 420 .isSameInstanceAs(service); 421 } 422 423 @Test declaringActionUnbindableMakesBindServiceReturnFalse()424 public void declaringActionUnbindableMakesBindServiceReturnFalse() { 425 shadowMainLooper().pause(); 426 TestService service = new TestService(); 427 ComponentName expectedComponentName = new ComponentName("", ""); 428 Binder expectedBinder = new Binder(); 429 Intent expectedIntent = new Intent("refuseToBind").setPackage("package"); 430 Shadows.shadowOf(context) 431 .setComponentNameAndServiceForBindServiceForIntent( 432 expectedIntent, expectedComponentName, expectedBinder); 433 Shadows.shadowOf(context).declareActionUnbindable(expectedIntent.getAction()); 434 assertFalse(context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE)); 435 shadowMainLooper().idle(); 436 assertThat(service.name).isNull(); 437 assertThat(service.service).isNull(); 438 assertThat(Shadows.shadowOf(context).peekNextStartedService()).isNull(); 439 } 440 441 @Test declaringComponentUnbindableMakesBindServiceReturnFalse_intentWithComponent()442 public void declaringComponentUnbindableMakesBindServiceReturnFalse_intentWithComponent() { 443 shadowMainLooper().pause(); 444 TestService service = new TestService(); 445 ComponentName expectedComponentName = new ComponentName("unbindable", "service"); 446 Intent intent = new Intent("unbindable").setComponent(expectedComponentName); 447 Shadows.shadowOf(context).declareComponentUnbindable(expectedComponentName); 448 assertThat(context.bindService(intent, service, Context.BIND_AUTO_CREATE)).isFalse(); 449 shadowMainLooper().idle(); 450 assertThat(service.name).isNull(); 451 assertThat(service.service).isNull(); 452 assertThat(Shadows.shadowOf(context).peekNextStartedService()).isNull(); 453 } 454 455 @Test declaringComponentUnbindableMakesBindServiceReturnFalse_intentWithoutComponent()456 public void declaringComponentUnbindableMakesBindServiceReturnFalse_intentWithoutComponent() { 457 shadowMainLooper().pause(); 458 TestService service = new TestService(); 459 ComponentName expectedComponentName = new ComponentName("unbindable", "service"); 460 Binder expectedBinder = new Binder(); 461 Intent expectedIntent = new Intent("expected").setPackage("package"); 462 Shadows.shadowOf(context) 463 .setComponentNameAndServiceForBindServiceForIntent( 464 expectedIntent, expectedComponentName, expectedBinder); 465 Shadows.shadowOf(context).declareComponentUnbindable(expectedComponentName); 466 assertThat(context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE)).isFalse(); 467 shadowMainLooper().idle(); 468 assertThat(service.name).isNull(); 469 assertThat(service.service).isNull(); 470 assertThat(Shadows.shadowOf(context).peekNextStartedService()).isNull(); 471 } 472 473 @Test declaringComponentUnbindableMakesBindServiceReturnFalse_defaultComponent()474 public void declaringComponentUnbindableMakesBindServiceReturnFalse_defaultComponent() { 475 shadowMainLooper().pause(); 476 TestService service = new TestService(); 477 ComponentName expectedComponentName = new ComponentName("unbindable", "service"); 478 Binder expectedBinder = new Binder(); 479 Intent expectedIntent = new Intent("expected").setPackage("package"); 480 Shadows.shadowOf(context) 481 .setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder); 482 Shadows.shadowOf(context).declareComponentUnbindable(expectedComponentName); 483 assertThat(context.bindService(expectedIntent, service, Context.BIND_AUTO_CREATE)).isFalse(); 484 shadowMainLooper().idle(); 485 assertThat(service.name).isNull(); 486 assertThat(service.service).isNull(); 487 assertThat(Shadows.shadowOf(context).peekNextStartedService()).isNull(); 488 } 489 490 @Test bindServiceWithMultipleIntentsMapping()491 public void bindServiceWithMultipleIntentsMapping() { 492 TestService service = new TestService(); 493 ComponentName expectedComponentNameOne = new ComponentName("package", "one"); 494 Binder expectedBinderOne = new Binder(); 495 Intent expectedIntentOne = new Intent("expected_one").setPackage("package"); 496 ComponentName expectedComponentNameTwo = new ComponentName("package", "two"); 497 Binder expectedBinderTwo = new Binder(); 498 Intent expectedIntentTwo = new Intent("expected_two").setPackage("package"); 499 Shadows.shadowOf(context) 500 .setComponentNameAndServiceForBindServiceForIntent( 501 expectedIntentOne, expectedComponentNameOne, expectedBinderOne); 502 Shadows.shadowOf(context) 503 .setComponentNameAndServiceForBindServiceForIntent( 504 expectedIntentTwo, expectedComponentNameTwo, expectedBinderTwo); 505 context.bindService(expectedIntentOne, service, Context.BIND_AUTO_CREATE); 506 shadowMainLooper().idle(); 507 assertThat(service.name).isEqualTo(expectedComponentNameOne); 508 assertThat(service.service).isEqualTo(expectedBinderOne); 509 context.bindService(expectedIntentTwo, service, Context.BIND_AUTO_CREATE); 510 shadowMainLooper().idle(); 511 assertThat(service.name).isEqualTo(expectedComponentNameTwo); 512 assertThat(service.service).isEqualTo(expectedBinderTwo); 513 } 514 515 @Test bindServiceWithMultipleIntentsMappingWithDefault()516 public void bindServiceWithMultipleIntentsMappingWithDefault() { 517 TestService service = new TestService(); 518 ComponentName expectedComponentNameOne = new ComponentName("package", "one"); 519 Binder expectedBinderOne = new Binder(); 520 Intent expectedIntentOne = new Intent("expected_one").setPackage("package"); 521 ComponentName expectedComponentNameTwo = new ComponentName("package", "two"); 522 Binder expectedBinderTwo = new Binder(); 523 Intent expectedIntentTwo = new Intent("expected_two").setPackage("package"); 524 Shadows.shadowOf(context) 525 .setComponentNameAndServiceForBindServiceForIntent( 526 expectedIntentOne, expectedComponentNameOne, expectedBinderOne); 527 Shadows.shadowOf(context) 528 .setComponentNameAndServiceForBindServiceForIntent( 529 expectedIntentTwo, expectedComponentNameTwo, expectedBinderTwo); 530 context.bindService(expectedIntentOne, service, Context.BIND_AUTO_CREATE); 531 shadowMainLooper().idle(); 532 assertThat(service.name).isEqualTo(expectedComponentNameOne); 533 assertThat(service.service).isEqualTo(expectedBinderOne); 534 context.bindService(expectedIntentTwo, service, Context.BIND_AUTO_CREATE); 535 shadowMainLooper().idle(); 536 assertThat(service.name).isEqualTo(expectedComponentNameTwo); 537 assertThat(service.service).isEqualTo(expectedBinderTwo); 538 context.bindService( 539 new Intent("unknown").setPackage("package"), service, Context.BIND_AUTO_CREATE); 540 shadowMainLooper().idle(); 541 assertThat(service.name).isNull(); 542 assertThat(service.service).isNull(); 543 } 544 545 @Test unbindServiceWithMultipleIntentsMapping()546 public void unbindServiceWithMultipleIntentsMapping() { 547 TestService serviceOne = new TestService(); 548 ComponentName expectedComponentNameOne = new ComponentName("package", "one"); 549 Binder expectedBinderOne = new Binder(); 550 Intent expectedIntentOne = new Intent("expected_one").setPackage("package"); 551 TestService serviceTwo = new TestService(); 552 ComponentName expectedComponentNameTwo = new ComponentName("package", "two"); 553 Binder expectedBinderTwo = new Binder(); 554 Intent expectedIntentTwo = new Intent("expected_two").setPackage("package"); 555 Shadows.shadowOf(context) 556 .setComponentNameAndServiceForBindServiceForIntent( 557 expectedIntentOne, expectedComponentNameOne, expectedBinderOne); 558 Shadows.shadowOf(context) 559 .setComponentNameAndServiceForBindServiceForIntent( 560 expectedIntentTwo, expectedComponentNameTwo, expectedBinderTwo); 561 562 context.bindService(expectedIntentOne, serviceOne, Context.BIND_AUTO_CREATE); 563 shadowMainLooper().idle(); 564 assertThat(serviceOne.nameDisconnected).isNull(); 565 context.unbindService(serviceOne); 566 shadowMainLooper().idle(); 567 assertThat(serviceOne.name).isEqualTo(expectedComponentNameOne); 568 569 context.bindService(expectedIntentTwo, serviceTwo, Context.BIND_AUTO_CREATE); 570 shadowMainLooper().idle(); 571 assertThat(serviceTwo.nameDisconnected).isNull(); 572 context.unbindService(serviceTwo); 573 shadowMainLooper().idle(); 574 assertThat(serviceTwo.name).isEqualTo(expectedComponentNameTwo); 575 576 TestService serviceDefault = new TestService(); 577 context.bindService( 578 new Intent("default").setPackage("package"), serviceDefault, Context.BIND_AUTO_CREATE); 579 shadowMainLooper().idle(); 580 assertThat(serviceDefault.nameDisconnected).isNull(); 581 context.unbindService(serviceDefault); 582 shadowMainLooper().idle(); 583 assertThat(serviceDefault.name).isNull(); 584 } 585 586 @Test shouldHaveStoppedServiceIntentAndIndicateServiceWasntRunning()587 public void shouldHaveStoppedServiceIntentAndIndicateServiceWasntRunning() { 588 589 Activity activity = Robolectric.setupActivity(Activity.class); 590 591 Intent intent = getSomeActionIntent("some.action"); 592 593 boolean wasRunning = activity.stopService(intent); 594 595 assertFalse(wasRunning); 596 assertThat(Shadows.shadowOf(context).getNextStoppedService()).isEqualTo(intent); 597 } 598 getSomeActionIntent(String action)599 private Intent getSomeActionIntent(String action) { 600 Intent intent = new Intent(); 601 intent.setAction(action); 602 intent.setPackage("package"); 603 return intent; 604 } 605 606 @Test shouldHaveStoppedServiceIntentAndIndicateServiceWasRunning()607 public void shouldHaveStoppedServiceIntentAndIndicateServiceWasRunning() { 608 609 Activity activity = Robolectric.setupActivity(Activity.class); 610 611 Intent intent = getSomeActionIntent("some.action"); 612 613 activity.startService(intent); 614 615 boolean wasRunning = activity.stopService(intent); 616 617 assertTrue(wasRunning); 618 assertThat(shadowOf(context).getNextStoppedService()).isEqualTo(intent); 619 } 620 621 @Test shouldHaveStoppedServiceByStartedComponent()622 public void shouldHaveStoppedServiceByStartedComponent() { 623 624 Activity activity = Robolectric.setupActivity(Activity.class); 625 626 ComponentName componentName = new ComponentName("package.test", "package.test.TestClass"); 627 Intent startServiceIntent = new Intent().setComponent(componentName); 628 629 ComponentName startedComponent = activity.startService(startServiceIntent); 630 assertThat(startedComponent.getPackageName()).isEqualTo("package.test"); 631 assertThat(startedComponent.getClassName()).isEqualTo("package.test.TestClass"); 632 633 Intent stopServiceIntent = new Intent().setComponent(startedComponent); 634 stopServiceIntent.putExtra("someExtra", "someValue"); 635 boolean wasRunning = activity.stopService(stopServiceIntent); 636 637 assertTrue(wasRunning); 638 final Intent nextStoppedService = shadowOf(context).getNextStoppedService(); 639 assertThat(nextStoppedService.filterEquals(startServiceIntent)).isTrue(); 640 assertThat(nextStoppedService.getStringExtra("someExtra")).isEqualTo("someValue"); 641 } 642 643 @Test shouldClearStartedServiceIntents()644 public void shouldClearStartedServiceIntents() { 645 context.startService(getSomeActionIntent("some.action")); 646 context.startService(getSomeActionIntent("another.action")); 647 648 shadowOf(context).clearStartedServices(); 649 650 assertNull(shadowOf(context).getNextStartedService()); 651 } 652 653 @Test getAllStartedServices()654 public void getAllStartedServices() { 655 Intent intent1 = getSomeActionIntent("some.action"); 656 Intent intent2 = getSomeActionIntent("another.action"); 657 658 context.startService(intent1); 659 context.startService(intent2); 660 List<Intent> startedServiceIntents = shadowOf(context).getAllStartedServices(); 661 662 assertThat(startedServiceIntents).hasSize(2); 663 assertThat(startedServiceIntents.get(0).filterEquals(intent1)).isTrue(); 664 assertThat(startedServiceIntents.get(1).filterEquals(intent2)).isTrue(); 665 assertNotNull(shadowOf(context).getNextStartedService()); 666 assertNotNull(shadowOf(context).getNextStartedService()); 667 assertNull(shadowOf(context).getNextStartedService()); 668 } 669 670 @Test shouldThrowIfContainsRegisteredReceiverOfAction()671 public void shouldThrowIfContainsRegisteredReceiverOfAction() { 672 Activity activity = Robolectric.setupActivity(Activity.class); 673 activity.registerReceiver(new TestBroadcastReceiver(), new IntentFilter("Foo")); 674 675 try { 676 shadowOf(context).assertNoBroadcastListenersOfActionRegistered(activity, "Foo"); 677 678 fail("should have thrown IllegalStateException"); 679 } catch (IllegalStateException e) { 680 // ok 681 } 682 } 683 684 @Test shouldNotThrowIfDoesNotContainsRegisteredReceiverOfAction()685 public void shouldNotThrowIfDoesNotContainsRegisteredReceiverOfAction() { 686 Activity activity = Robolectric.setupActivity(Activity.class); 687 activity.registerReceiver(new TestBroadcastReceiver(), new IntentFilter("Foo")); 688 689 shadowOf(context).assertNoBroadcastListenersOfActionRegistered(activity, "Bar"); 690 } 691 692 @Test canAnswerIfReceiverIsRegisteredForIntent()693 public void canAnswerIfReceiverIsRegisteredForIntent() throws Exception { 694 BroadcastReceiver expectedReceiver = new TestBroadcastReceiver(); 695 assertFalse(shadowOf(context).hasReceiverForIntent(new Intent("Foo"))); 696 context.registerReceiver(expectedReceiver, new IntentFilter("Foo")); 697 698 assertTrue(shadowOf(context).hasReceiverForIntent(new Intent("Foo"))); 699 } 700 701 @Test canFindAllReceiversForAnIntent()702 public void canFindAllReceiversForAnIntent() throws Exception { 703 BroadcastReceiver expectedReceiver = new TestBroadcastReceiver(); 704 assertFalse(shadowOf(context).hasReceiverForIntent(new Intent("Foo"))); 705 context.registerReceiver(expectedReceiver, new IntentFilter("Foo")); 706 context.registerReceiver(expectedReceiver, new IntentFilter("Foo")); 707 708 assertThat(shadowOf(context).getReceiversForIntent(new Intent("Foo"))).hasSize(2); 709 } 710 711 @Test broadcasts_shouldBeLogged()712 public void broadcasts_shouldBeLogged() { 713 Intent broadcastIntent = new Intent("foo"); 714 context.sendBroadcast(broadcastIntent); 715 716 List<Intent> broadcastIntents = shadowOf(context).getBroadcastIntents(); 717 assertThat(broadcastIntents).hasSize(1); 718 assertThat(broadcastIntents.get(0)).isEqualTo(broadcastIntent); 719 } 720 721 @Test clearRegisteredReceivers_clearsReceivers()722 public void clearRegisteredReceivers_clearsReceivers() { 723 Activity activity = Robolectric.setupActivity(Activity.class); 724 activity.registerReceiver(new TestBroadcastReceiver(), new IntentFilter("Foo")); 725 726 assertThat(shadowOf(context).getRegisteredReceivers().size()).isAtLeast(1); 727 728 shadowOf(context).clearRegisteredReceivers(); 729 730 assertThat(shadowOf(context).getRegisteredReceivers()).isEmpty(); 731 } 732 733 @Test sendStickyBroadcast()734 public void sendStickyBroadcast() { 735 Intent broadcastIntent = new Intent("Foo"); 736 context.sendStickyBroadcast(broadcastIntent); 737 738 // Register after the broadcast has fired. We should immediately get a sticky event. 739 TestBroadcastReceiver receiver = new TestBroadcastReceiver(); 740 context.registerReceiver(receiver, new IntentFilter("Foo")); 741 assertTrue(receiver.isSticky); 742 743 // Fire the broadcast again, and we should get a non-sticky event. 744 context.sendStickyBroadcast(broadcastIntent); 745 shadowMainLooper().idle(); 746 assertFalse(receiver.isSticky); 747 } 748 749 @Test sendBroadcastWithPermission()750 public void sendBroadcastWithPermission() { 751 Intent broadcastIntent = new Intent("Foo"); 752 String permission = "org.robolectric.SOME_PERMISSION"; 753 754 TestBroadcastReceiver receiverWithoutPermission = new TestBroadcastReceiver(); 755 context.registerReceiver(receiverWithoutPermission, new IntentFilter("Foo")); 756 TestBroadcastReceiver receiverWithPermission = new TestBroadcastReceiver(); 757 context.registerReceiver( 758 receiverWithPermission, new IntentFilter("Foo"), permission, /* scheduler= */ null); 759 760 context.sendBroadcast(broadcastIntent); 761 shadowMainLooper().idle(); 762 assertThat(receiverWithoutPermission.intent).isEqualTo(broadcastIntent); 763 assertThat(receiverWithPermission.intent).isNull(); 764 receiverWithoutPermission.intent = null; 765 766 shadowOf(context).grantPermissions(permission); 767 context.sendBroadcast(broadcastIntent); 768 shadowMainLooper().idle(); 769 assertThat(receiverWithoutPermission.intent).isEqualTo(broadcastIntent); 770 assertThat(receiverWithPermission.intent).isEqualTo(broadcastIntent); 771 } 772 773 @Test shouldRememberResourcesAfterLazilyLoading()774 public void shouldRememberResourcesAfterLazilyLoading() throws Exception { 775 assertSame(context.getResources(), context.getResources()); 776 } 777 778 @Test startActivity_whenActivityCheckingEnabled_doesntFindResolveInfo()779 public void startActivity_whenActivityCheckingEnabled_doesntFindResolveInfo() throws Exception { 780 shadowOf(context).checkActivities(true); 781 782 String action = "com.does.not.exist.android.app.v2.mobile"; 783 784 try { 785 context.startActivity(new Intent(action).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); 786 fail("Expected startActivity to throw ActivityNotFoundException!"); 787 } catch (ActivityNotFoundException e) { 788 assertThat(e.getMessage()).contains(action); 789 assertThat(shadowOf(context).getNextStartedActivity()).isNull(); 790 } 791 } 792 793 @Test startActivity_whenActivityCheckingEnabled_findsResolveInfo()794 public void startActivity_whenActivityCheckingEnabled_findsResolveInfo() throws Exception { 795 shadowOf(context).checkActivities(true); 796 797 context.startActivity( 798 new Intent() 799 .setClassName(context, TestActivity.class.getName()) 800 .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); 801 802 assertThat(shadowOf(context).getNextStartedActivity()).isNotNull(); 803 } 804 805 @Test bindServiceShouldAddServiceConnectionToListOfBoundServiceConnections()806 public void bindServiceShouldAddServiceConnectionToListOfBoundServiceConnections() { 807 final ServiceConnection expectedServiceConnection = new EmptyServiceConnection(); 808 809 assertThat(Shadows.shadowOf(context).getBoundServiceConnections()).hasSize(0); 810 assertThat( 811 context.bindService( 812 new Intent("connect").setPackage("dummy.package"), expectedServiceConnection, 0)) 813 .isTrue(); 814 assertThat(Shadows.shadowOf(context).getBoundServiceConnections()).hasSize(1); 815 assertThat(Shadows.shadowOf(context).getBoundServiceConnections().get(0)) 816 .isSameInstanceAs(expectedServiceConnection); 817 } 818 819 @Test 820 public void bindServiceShouldAddServiceConnectionToListOfBoundServiceConnectionsEvenIfServiceUnbindable()821 bindServiceShouldAddServiceConnectionToListOfBoundServiceConnectionsEvenIfServiceUnbindable() { 822 final ServiceConnection expectedServiceConnection = new EmptyServiceConnection(); 823 final String unboundableAction = "refuse"; 824 final Intent serviceIntent = new Intent(unboundableAction).setPackage("dummy.package"); 825 Shadows.shadowOf(context).declareActionUnbindable(unboundableAction); 826 assertThat(Shadows.shadowOf(context).getBoundServiceConnections()).hasSize(0); 827 assertThat(context.bindService(serviceIntent, expectedServiceConnection, 0)).isFalse(); 828 assertThat(Shadows.shadowOf(context).getBoundServiceConnections()).hasSize(1); 829 assertThat(Shadows.shadowOf(context).getBoundServiceConnections().get(0)) 830 .isSameInstanceAs(expectedServiceConnection); 831 } 832 833 @Test unbindServiceShouldRemoveServiceConnectionFromListOfBoundServiceConnections()834 public void unbindServiceShouldRemoveServiceConnectionFromListOfBoundServiceConnections() { 835 final ServiceConnection expectedServiceConnection = new EmptyServiceConnection(); 836 837 assertThat( 838 context.bindService( 839 new Intent("connect").setPackage("dummy.package"), expectedServiceConnection, 0)) 840 .isTrue(); 841 assertThat(Shadows.shadowOf(context).getBoundServiceConnections()).hasSize(1); 842 assertThat(Shadows.shadowOf(context).getUnboundServiceConnections()).hasSize(0); 843 context.unbindService(expectedServiceConnection); 844 assertThat(Shadows.shadowOf(context).getBoundServiceConnections()).hasSize(0); 845 assertThat(Shadows.shadowOf(context).getUnboundServiceConnections()).hasSize(1); 846 assertThat(Shadows.shadowOf(context).getUnboundServiceConnections().get(0)) 847 .isSameInstanceAs(expectedServiceConnection); 848 } 849 850 @Test getForegroundThreadScheduler_shouldMatchRobolectricValue()851 public void getForegroundThreadScheduler_shouldMatchRobolectricValue() { 852 assertThat(Shadows.shadowOf(context).getForegroundThreadScheduler()) 853 .isSameInstanceAs(Robolectric.getForegroundThreadScheduler()); 854 } 855 856 @Test 857 @LooperMode(LEGACY) getBackgroundThreadScheduler_shouldMatchRobolectricValue()858 public void getBackgroundThreadScheduler_shouldMatchRobolectricValue() { 859 assertThat(Shadows.shadowOf(context).getBackgroundThreadScheduler()) 860 .isSameInstanceAs(Robolectric.getBackgroundThreadScheduler()); 861 } 862 863 @Test getForegroundThreadScheduler_shouldMatchRuntimeEnvironment()864 public void getForegroundThreadScheduler_shouldMatchRuntimeEnvironment() { 865 Scheduler s = new Scheduler(); 866 RuntimeEnvironment.setMasterScheduler(s); 867 assertThat(Shadows.shadowOf(context).getForegroundThreadScheduler()).isSameInstanceAs(s); 868 } 869 870 @Test 871 @LooperMode(LEGACY) getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_byDefault()872 public void getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_byDefault() { 873 Scheduler s = new Scheduler(); 874 RuntimeEnvironment.setMasterScheduler(s); 875 assertThat(Shadows.shadowOf(context).getBackgroundThreadScheduler()) 876 .isNotSameInstanceAs(RuntimeEnvironment.getMasterScheduler()); 877 } 878 879 @Test 880 @LooperMode(LEGACY) 881 public void getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_withAdvancedScheduling()882 getBackgroundThreadScheduler_shouldDifferFromRuntimeEnvironment_withAdvancedScheduling() { 883 Scheduler s = new Scheduler(); 884 RuntimeEnvironment.setMasterScheduler(s); 885 assertThat(Shadows.shadowOf(context).getBackgroundThreadScheduler()).isNotSameInstanceAs(s); 886 } 887 888 @Test getLatestPopupWindow()889 public void getLatestPopupWindow() { 890 PopupWindow pw = new PopupWindow(new LinearLayout(context)); 891 892 pw.showAtLocation(new LinearLayout(context), Gravity.CENTER, 0, 0); 893 894 PopupWindow latestPopupWindow = 895 Shadows.shadowOf(RuntimeEnvironment.getApplication()).getLatestPopupWindow(); 896 assertThat(latestPopupWindow).isSameInstanceAs(pw); 897 } 898 899 @Test 900 @Config(minSdk = VERSION_CODES.P) shouldReturnNonDefaultProcessName()901 public void shouldReturnNonDefaultProcessName() { 902 ShadowApplication.setProcessName("org.foo:bar"); 903 assertThat(Application.getProcessName()).isEqualTo("org.foo:bar"); 904 } 905 906 ///////////////////////////// 907 908 private static class EmptyServiceConnection implements ServiceConnection { 909 @Override onServiceConnected(ComponentName name, IBinder service)910 public void onServiceConnected(ComponentName name, IBinder service) {} 911 912 @Override onServiceDisconnected(ComponentName name)913 public void onServiceDisconnected(ComponentName name) {} 914 } 915 916 public static class TestBroadcastReceiver extends BroadcastReceiver { 917 public Context context; 918 public Intent intent; 919 public boolean isSticky; 920 921 @Override onReceive(Context context, Intent intent)922 public void onReceive(Context context, Intent intent) { 923 this.context = context; 924 this.intent = intent; 925 this.isSticky = isInitialStickyBroadcast(); 926 } 927 } 928 } 929