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