Java 类org.robolectric.shadows.ShadowApplication 实例源码

项目:q-mail    文件:RecipientPresenterTest.java   
@Before
public void setUp() throws Exception {
    Context context = ShadowApplication.getInstance().getApplicationContext();
    Robolectric.getBackgroundThreadScheduler().pause();

    recipientMvpView = mock(RecipientMvpView.class);
    account = mock(Account.class);
    composePgpInlineDecider = mock(ComposePgpInlineDecider.class);
    composePgpEnableByDefaultDecider = mock(ComposePgpEnableByDefaultDecider.class);
    autocryptStatusInteractor = mock(AutocryptStatusInteractor.class);
    replyToParser = mock(ReplyToParser.class);
    LoaderManager loaderManager = mock(LoaderManager.class);
    listener = mock(RecipientPresenter.RecipientsChangedListener.class);

    recipientPresenter = new RecipientPresenter(
            context, loaderManager, recipientMvpView, account, composePgpInlineDecider,
            composePgpEnableByDefaultDecider, autocryptStatusInteractor, replyToParser, listener);
    runBackgroundTask();

    noRecipientsAutocryptResult = new RecipientAutocryptStatus(RecipientAutocryptStatusType.NO_RECIPIENTS, null);
}
项目:JobSchedulerCompat    文件:JobGcReceiverTest.java   
@Test
public void testBootReceiverRegistered() {
    Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
    AndroidManifest manifest = ShadowApplication.getInstance().getAppManifest();
    List<BroadcastReceiver> receivers = ShadowApplication.getInstance().getReceiversForIntent(intent);
    assertThat(receivers, hasItem(isA(JobGcReceiver.class)));
}
项目:JobSchedulerCompat    文件:AlarmContentObserverServiceTest.java   
@Test
public void testObserversFire() {
    Uri[] uris = new Uri[]{Uri.parse("doist.com"), Uri.parse("todoist.com"), Uri.parse("twistapp.com")};

    for (int i = 0; i < uris.length; i++) {
        jobStore.add(JobStatus.createFromJobInfo(
                JobCreator.create(context, i, 5000)
                          .addTriggerContentUri(new JobInfo.TriggerContentUri(uris[i], 0))
                          .build(),
                AlarmScheduler.TAG));
    }
    service.startCommand(0, 0);

    ShadowApplication application = ShadowApplication.getInstance();
    ShadowContentResolver contentResolver = shadowOf(context.getContentResolver());
    for (Uri uri : uris) {
        assertEquals(0, application.getBoundServiceConnections().size());
        assertEquals(1, contentResolver.getContentObservers(uri).size());
        contentResolver.notifyChange(uri, null);
        DeviceTestUtils.advanceTime(JobStatus.DEFAULT_TRIGGER_MAX_DELAY);
        assertEquals(1, contentResolver.getContentObservers(uri).size());
        assertEquals(AlarmJobService.class.getCanonicalName(),
                     application.getNextStartedService().getComponent().getClassName());
    }
}
项目:JobSchedulerCompat    文件:AlarmReceiverTest.java   
@Test
public void testReceiversStartService() {
    new AlarmReceiver().onReceive(context, new Intent(Intent.ACTION_BOOT_COMPLETED));

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());

    new AlarmReceiver.BatteryReceiver().onReceive(context, new Intent(Intent.ACTION_POWER_CONNECTED));

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());

    new AlarmReceiver.StorageReceiver().onReceive(context, new Intent(Intent.ACTION_DEVICE_STORAGE_LOW));

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());

    new AlarmReceiver.ConnectivityReceiver().onReceive(
            context, new Intent(ConnectivityManager.CONNECTIVITY_ACTION));

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());
}
项目:weex-analyzer-android    文件:LaunchAnalyzerReceiverTest.java   
@Test
public void onReceive() throws Exception {

    //one
    ShadowApplication application = ShadowApplication.getInstance();
    Intent intent = new Intent(ACTION);
    boolean result = application.hasReceiverForIntent(intent);
    assertTrue(result);

    //only one
    List<BroadcastReceiver> receivers = application.getReceiversForIntent(intent);
    assertEquals(1,receivers.size());

    //test onReceive
    intent.putExtra("c","off");
    BroadcastReceiver targetReceiver = receivers.get(0);
    targetReceiver.onReceive(application.getApplicationContext(),intent);

    Intent serviceIntent = application.getNextStoppedService();
    assertEquals(serviceIntent.getComponent().getClassName(),AnalyzerService.class.getCanonicalName());
}
项目:circleflow-android    文件:DeviceEventHandlerTest.java   
@Test
public void testSendSignalDirectly() {
    DeviceEventHandler handler = new DeviceEventHandler();
    DeviceEvent event = new DeviceEvent();
    event.setName("device1");
    event.setData("key1", "value1");
    event.setData("key2", 2);
    handler.sendSignal(event);

    List<Intent> intents = ShadowApplication.getInstance().getBroadcastIntents();
    Assert.assertEquals(1, intents.size());
    Intent intent = intents.get(0);
    Assert.assertEquals("com.mocircle.flow.actions.ACTION_SEND_DEVICE_EVENT", intent.getAction());
    Assert.assertEquals("device1", intent.getStringExtra("extra_event_name"));
    HashMap<String, Object> data = (HashMap) intent.getSerializableExtra("extra_event_data");
    Assert.assertEquals("value1", data.get("key1"));
    Assert.assertEquals(2, data.get("key2"));
}
项目:loadie    文件:CursorLoaderTest.java   
@Test
public void cancelClosesCursorIfLoading() {
    CursorLoader loader = new CursorLoader.Builder(resolver, CONTENT_URI).build();
    Loader.Callbacks<Cursor> callbacks = mock(Loader.Callbacks.class);
    loader.setCallbacks(callbacks);

    background.pause();

    loader.start();
    loader.cancel();

    background.unPause();
    ShadowApplication.runBackgroundTasks();

    assertTrue(cursor.isClosed());
}
项目:materialistic    文件:AppUtilsTest.java   
@Test
public void testSetTextWithLinks() {
    TestApplication.addResolver(new Intent(Intent.ACTION_VIEW, Uri.parse("http://example.com")));
    Preferences.set(RuntimeEnvironment.application, R.string.pref_custom_tab, false);
    TextView textView = new TextView(RuntimeEnvironment.application);
    AppUtils.setTextWithLinks(textView, AppUtils.fromHtml("<a href=\"http://example.com\">http://example.com</a>"));
    MotionEvent event = mock(MotionEvent.class);
    when(event.getAction()).thenReturn(MotionEvent.ACTION_DOWN);
    when(event.getX()).thenReturn(0f);
    when(event.getY()).thenReturn(0f);
    assertTrue(shadowOf(textView).getOnTouchListener().onTouch(textView, event));
    when(event.getAction()).thenReturn(MotionEvent.ACTION_UP);
    when(event.getX()).thenReturn(0f);
    when(event.getY()).thenReturn(0f);
    assertTrue(shadowOf(textView).getOnTouchListener().onTouch(textView, event));
    assertNotNull(ShadowApplication.getInstance().getNextStartedActivity());
}
项目:materialistic    文件:AppUtilsTest.java   
@Test
public void testSetTextWithLinksOpenChromeCustomTabs() {
    TestApplication.addResolver(new Intent(Intent.ACTION_VIEW, Uri.parse("http://example.com")));
    TextView textView = new TextView(new ContextThemeWrapper(RuntimeEnvironment.application, R.style.AppTheme));
    AppUtils.setTextWithLinks(textView, AppUtils.fromHtml("<a href=\"http://example.com\">http://example.com</a>"));
    MotionEvent event = mock(MotionEvent.class);
    when(event.getAction()).thenReturn(MotionEvent.ACTION_DOWN);
    when(event.getX()).thenReturn(0f);
    when(event.getY()).thenReturn(0f);
    assertTrue(shadowOf(textView).getOnTouchListener().onTouch(textView, event));
    when(event.getAction()).thenReturn(MotionEvent.ACTION_UP);
    when(event.getX()).thenReturn(0f);
    when(event.getY()).thenReturn(0f);
    assertTrue(shadowOf(textView).getOnTouchListener().onTouch(textView, event));
    assertNotNull(ShadowApplication.getInstance().getNextStartedActivity());
}
项目:goro    文件:BaseBindingGoroTest.java   
@Before
public void init() {
  context = Robolectric.setupActivity(Activity.class);
  shadowContext = Shadows.shadowOf(context);

  testingQueues = new TestingQueues();
  serviceInstance = spy(new Goro.GoroImpl(testingQueues));

  serviceCompName = new ComponentName(context, GoroService.class);
  GoroService service = new GoroService();
  binder = new GoroService.GoroBinderImpl(serviceInstance, service.new GoroTasksListener());
  ShadowApplication.getInstance()
      .setComponentNameAndServiceForBindService(
          serviceCompName,
          binder
      );
  reset(serviceInstance);
}
项目:grocery-reminder    文件:GroceryStoreNotificationManagerTest.java   
@Test
public void whenANotificationIsSentThenTheTheNotificationIncludesTheStoreName() {
    ShadowApplication shadowApplication = (ShadowApplication) Shadows.shadowOf(RuntimeEnvironment.application);

    insertStoreLocation(shadowApplication);

    ShadowLocation.setDistanceBetween(new float[]{(float) GroceryReminderConstants.LOCATION_GEOFENCE_RADIUS_METERS});

    long currentTime = System.currentTimeMillis();
    groceryStoreNotificationManager.sendPotentialNotification(new Location(LocationManager.GPS_PROVIDER), currentTime);

    ShadowNotificationManager shadowNotificationManager = getShadowNotificationManager();
    Notification notification = shadowNotificationManager.getNotification(GroceryReminderConstants.NOTIFICATION_PROXIMITY_ALERT);
    ShadowNotification shadowNotification = (ShadowNotification)Shadows.shadowOf(notification);
    assertTrue(((String) shadowNotification.getContentTitle()).contains(ARBITRARY_STORE_NAME));
}
项目:grocery-reminder    文件:GroceryStoreNotificationManagerTest.java   
@Test
 public void givenAStoreNotificationHasBeenStoredWhenARequestToSendANotificationWithTheTheSameStoreIsReceivedBeforeTheMinimumUpdateTimeForTheSameStoreThenTheNotificationIsNotSent() {
    ShadowApplication shadowApplication = (ShadowApplication) Shadows.shadowOf(RuntimeEnvironment.application);

    insertStoreLocation(shadowApplication);
    SharedPreferences sharedPreferences = shadowApplication.getSharedPreferences(shadowApplication.getString(R.string.reminder_pref_key), Context.MODE_PRIVATE);
    sharedPreferences.edit().putString(GroceryReminderConstants.LAST_NOTIFIED_STORE_KEY, ARBITRARY_STORE_NAME)
            .putLong(GroceryReminderConstants.LAST_NOTIFICATION_TIME_FOR_SAME_STORE, System.currentTimeMillis() - 1)
            .commit();

    ShadowLocation.setDistanceBetween(new float[]{(float) GroceryReminderConstants.LOCATION_GEOFENCE_RADIUS_METERS});

    ShadowNotificationManager shadowNotificationManager = getShadowNotificationManager();

    groceryStoreNotificationManager.sendPotentialNotification(new Location(LocationManager.GPS_PROVIDER), System.currentTimeMillis());

    Notification notification = shadowNotificationManager.getNotification(GroceryReminderConstants.NOTIFICATION_PROXIMITY_ALERT);
    assertNull(notification);
}
项目:grocery-reminder    文件:GroceryStoreNotificationManagerTest.java   
@Test
public void givenAStoreNotificationHasBeenStoredWhenARequestToSendANotificationWithTheTheSameStoreAfterTheMinimumUpdateTimeForTheSameStoreIsReceivedThenTheNotificationIsSent() {
    ShadowApplication shadowApplication = (ShadowApplication) Shadows.shadowOf(RuntimeEnvironment.application);

    insertStoreLocation(shadowApplication);
    SharedPreferences sharedPreferences = shadowApplication.getSharedPreferences(shadowApplication.getString(R.string.reminder_pref_key), Context.MODE_PRIVATE);
    sharedPreferences.edit()
            .putString(GroceryReminderConstants.LAST_NOTIFIED_STORE_KEY, ARBITRARY_STORE_NAME)
            .putLong(GroceryReminderConstants.LAST_NOTIFICATION_TIME_FOR_SAME_STORE, GroceryReminderConstants.MIN_LOCATION_UPDATE_TIME_FOR_SAME_STORE_MILLIS + 1)
            .commit();

    ShadowLocation.setDistanceBetween(new float[]{(float) GroceryReminderConstants.LOCATION_GEOFENCE_RADIUS_METERS});

    ShadowNotificationManager shadowNotificationManager = getShadowNotificationManager();

    groceryStoreNotificationManager.sendPotentialNotification(new Location(LocationManager.GPS_PROVIDER), System.currentTimeMillis());

    Notification notification = shadowNotificationManager.getNotification(GroceryReminderConstants.NOTIFICATION_PROXIMITY_ALERT);
    assertNotNull(notification);
}
项目:grocery-reminder    文件:GroceryStoreNotificationManagerTest.java   
@Test
public void givenAStoreNotificationHasBeenSentWhenARequestToSendANotificationIsReceivedUnderTheMinimumLocationUpdateTimeThenTheNotificationIsNotSent() {
    ShadowApplication shadowApplication = (ShadowApplication) Shadows.shadowOf(RuntimeEnvironment.application);

    insertStoreLocation(shadowApplication);
    SharedPreferences sharedPreferences = shadowApplication.getSharedPreferences(shadowApplication.getString(R.string.reminder_pref_key), Context.MODE_PRIVATE);
    sharedPreferences.edit()
            .putString(GroceryReminderConstants.LAST_NOTIFIED_STORE_KEY, ARBITRARY_STORE_NAME + 1)
            .putLong(GroceryReminderConstants.LAST_NOTIFICATION_TIME, System.currentTimeMillis())
            .commit();

    ShadowLocation.setDistanceBetween(new float[]{(float) GroceryReminderConstants.LOCATION_GEOFENCE_RADIUS_METERS});

    ShadowNotificationManager shadowNotificationManager = getShadowNotificationManager();

    groceryStoreNotificationManager.sendPotentialNotification(new Location(LocationManager.GPS_PROVIDER), System.currentTimeMillis());

    Notification notification = shadowNotificationManager.getNotification(GroceryReminderConstants.NOTIFICATION_PROXIMITY_ALERT);
    assertNull(notification);
}
项目:retain-state    文件:CursorLoaderTest.java   
@Test
public void cancelClosesCursorIfLoading() {
    CursorLoader loader = new CursorLoader.Builder(resolver, CONTENT_URI).build();
    Loader.Callbacks<Cursor> callbacks = mock(Loader.Callbacks.class);
    loader.setCallbacks(callbacks);

    background.pause();

    loader.start();
    loader.cancel();

    background.unPause();
    ShadowApplication.runBackgroundTasks();

    assertTrue(cursor.isClosed());
}
项目:lmis-moz-mobile    文件:RnRFormListActivityTest.java   
@Test
public void shouldStartVIAHistoryWhenBtnClickedWithTypeHistory() throws Exception {
    View view = mock(View.class);

    intent.putExtra(Constants.PARAM_PROGRAM_CODE, Constants.VIA_PROGRAM_CODE);
    rnRFormListActivity = Robolectric.buildActivity(RnRFormListActivity.class).withIntent(intent).create().get();

    RnRFormViewModel viewModel = generateRnRFormViewModel("ESS_MEDS", RnRFormViewModel.TYPE_SYNCED_HISTORICAL);
    viewModel.setId(999L);
    rnRFormListActivity.rnRFormItemClickListener.clickBtnView(viewModel, view);

    Intent nextStartedIntent = ShadowApplication.getInstance().getNextStartedActivity();

    assertNotNull(nextStartedIntent);
    assertEquals(nextStartedIntent.getComponent().getClassName(), VIARequisitionActivity.class.getName());
    assertEquals(nextStartedIntent.getLongExtra(Constants.PARAM_FORM_ID, 0), 999L);
}
项目:lmis-moz-mobile    文件:RnRFormListActivityTest.java   
@Test
public void shouldNotLoadSameFormIdAfterLoadedViaHistoryForm() throws Exception {
    View view = mock(View.class);

    RnRFormViewModel historyViewModel = generateRnRFormViewModel("MMIA", RnRFormViewModel.TYPE_SYNCED_HISTORICAL);
    historyViewModel.setId(1L);
    rnRFormListActivity.rnRFormItemClickListener.clickBtnView(historyViewModel, view);

    Intent startedIntentWhenIsHistory = ShadowApplication.getInstance().getNextStartedActivity();

    assertNotNull(startedIntentWhenIsHistory);
    assertEquals(startedIntentWhenIsHistory.getComponent().getClassName(), MMIARequisitionActivity.class.getName());
    assertEquals(1L, startedIntentWhenIsHistory.getLongExtra(Constants.PARAM_FORM_ID, 0));

    RnRFormViewModel defaultViewModel = generateRnRFormViewModel("MMIA", RnRFormViewModel.TYPE_CREATED_BUT_UNCOMPLETED);
    rnRFormListActivity.rnRFormItemClickListener.clickBtnView(defaultViewModel, view);

    Intent startedIntentWhenIsDefault = ShadowApplication.getInstance().getNextStartedActivity();

    assertNotNull(startedIntentWhenIsDefault);
    assertEquals(startedIntentWhenIsDefault.getComponent().getClassName(), MMIARequisitionActivity.class.getName());
    assertEquals(0L, startedIntentWhenIsDefault.getLongExtra(Constants.PARAM_FORM_ID, 0));
}
项目:lmis-moz-mobile    文件:RnRFormListActivityTest.java   
@Test
public void shouldGoToRequisitionPageWhenInvokeOnActivityResultWithSelectPeriodRequestCode() throws Exception {
    Intent data = new Intent();
    Date inventoryDate = new Date();
    data.putExtra(Constants.PARAM_SELECTED_INVENTORY_DATE, inventoryDate);
    data.putExtra(Constants.PARAM_IS_MISSED_PERIOD, true);

    intent.putExtra(Constants.PARAM_PROGRAM_CODE, Constants.VIA_PROGRAM_CODE);
    rnRFormListActivity = Robolectric.buildActivity(RnRFormListActivity.class).withIntent(intent).create().get();

    rnRFormListActivity.onActivityResult(Constants.REQUEST_SELECT_PERIOD_END, Activity.RESULT_OK, data);

    Intent nextStartedIntent = ShadowApplication.getInstance().getNextStartedActivity();

    assertNotNull(nextStartedIntent);
    assertEquals(nextStartedIntent.getComponent().getClassName(), VIARequisitionActivity.class.getName());

    assertTrue(nextStartedIntent.getBooleanExtra(Constants.PARAM_IS_MISSED_PERIOD, false));
    assertEquals(nextStartedIntent.getSerializableExtra(Constants.PARAM_SELECTED_INVENTORY_DATE), inventoryDate);
}
项目:edx-app-android    文件:BaseFragmentActivityTest.java   
/**
 * Generic method for asserting view animation method functionality
 *
 * @param view    The animated view
 * @param trigger A {@link Runnable} that triggers the animation
 */
protected void assertAnimateLayouts(View view, Runnable trigger) {
    // The foreground scheduler needs to be paused so that the
    // temporary visibility of the animated View can be verified.
    Scheduler foregroundScheduler = ShadowApplication.getInstance()
            .getForegroundThreadScheduler();
    boolean wasPaused = foregroundScheduler.isPaused();
    if (!wasPaused) {
        foregroundScheduler.pause();
    }
    assertThat(view).isGone();
    trigger.run();
    assertThat(view).isVisible();
    Animation animation = view.getAnimation();
    assertNotNull(animation);
    assertThat(animation.getStartTime())
            .isLessThanOrEqualTo(AnimationUtils.currentAnimationTimeMillis());
    assertThat(animation).hasStartOffset(0);
    foregroundScheduler.unPause();
    assertThat(view).isGone();
    if (wasPaused) {
        foregroundScheduler.pause();
    }
}
项目:android-beacon-library    文件:RangingDataTest.java   
@Test
// On MacBookPro 2.5 GHz Core I7, 10000 serialization/deserialiation cycles of RangingData took 22ms
public void testSerializationBenchmark() throws Exception {
    Context context = ShadowApplication.getInstance().getApplicationContext();
    ArrayList<Identifier> identifiers = new ArrayList<Identifier>();
    identifiers.add(Identifier.parse("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6"));
    identifiers.add(Identifier.parse("1"));
    identifiers.add(Identifier.parse("2"));
    Region region = new Region("testRegion", identifiers);
    ArrayList<Beacon> beacons = new ArrayList<Beacon>();
    Beacon beacon = new Beacon.Builder().setIdentifiers(identifiers).setRssi(-1).setRunningAverageRssi(-2).setTxPower(-50).setBluetoothAddress("01:02:03:04:05:06").build();
    for (int i=0; i < 10; i++) {
        beacons.add(beacon);
    }
    RangingData data = new RangingData(beacons, region);
    long time1 = System.currentTimeMillis();
    for (int i=0; i< 10000; i++) {
        Bundle bundle = data.toBundle();
        RangingData data2 = RangingData.fromBundle(bundle);
    }
    long time2 = System.currentTimeMillis();
    System.out.println("*** Ranging Data Serialization benchmark: "+(time2-time1));
}
项目:android-beacon-library    文件:BeaconTransmitterTest.java   
@Test
public void testBeaconAdvertisingBytesForEddystone() {
    org.robolectric.shadows.ShadowLog.stream = System.err;
    Context context = ShadowApplication.getInstance().getApplicationContext();

    Beacon beacon = new Beacon.Builder()
            .setId1("0x2f234454f4911ba9ffa6")
            .setId2("0x000000000001")
            .setManufacturer(0x0118)
            .setTxPower(-59)
            .build();
    BeaconParser beaconParser = new BeaconParser()
            .setBeaconLayout("s:0-1=feaa,m:2-2=00,p:3-3:-41,i:4-13,i:14-19");
    byte[] data = beaconParser.getBeaconAdvertisementData(beacon);
    BeaconTransmitter beaconTransmitter = new BeaconTransmitter(context, beaconParser);
    // TODO: can't actually start transmitter here because Robolectric does not support API 21

    String byteString = "";
    for (int i = 0; i < data.length; i++) {
        byteString += String.format("%02X", data[i]);
        byteString += " ";
    }
    Log.d(TAG, "Advertising bytes are "+byteString );
    assertEquals("Data should be 24 bytes long", 18, data.length);
    assertEquals("Advertisement bytes should be as expected", "00 C5 2F 23 44 54 F4 91 1B A9 FF A6 00 00 00 00 00 01 ", byteString);
}
项目:open    文件:RouteFragmentTest.java   
@Test @SuppressLint("NewApi")
public void shouldKillNotificationOnExitNavigation() throws Exception {
    ArrayList<Instruction> instructions = new ArrayList<Instruction>();
    Instruction instruction = getTestInstruction(3, 3);
    instructions.add(instruction);
    fragment.setInstructions(instructions);
    TestHelper.startFragment(fragment, act);
    fragment.onPageSelected(0);

    ShadowNotification sNotification = getRoutingNotification();
    sNotification.getActions().get(0).actionIntent.send();

    ShadowApplication application = shadowOf(act.getApplication());
    Intent broadcastIntent = application.getBroadcastIntents().get(0);
    String broadcastClassName = broadcastIntent.getComponent().getClassName();
    boolean shouldExit = broadcastIntent.getExtras()
            .getBoolean(MapzenNotificationCreator.EXIT_NAVIGATION);
    assertThat(shouldExit).isTrue();
    assertThat(broadcastClassName)
            .isEqualTo("com.mapzen.open.util.NotificationBroadcastReceiver");
}
项目:PanicButton    文件:HardwareTriggerServiceTest.java   
@Test
public void shouldRegisterHardwareTriggerListener() {
    HardwareTriggerService hardwareTriggerService = new HardwareTriggerService();
    hardwareTriggerService.onCreate();
    hardwareTriggerService.onBind(null);

    ShadowApplication shadowApplication = shadowOf(Robolectric.application);
    List<ShadowApplication.Wrapper> registeredReceivers = shadowApplication.getRegisteredReceivers();

    ShadowApplication.Wrapper hardwareReceiverWrapper = null;
    for (ShadowApplication.Wrapper registeredReceiver : registeredReceivers) {
        if (registeredReceiver.getBroadcastReceiver().getClass().equals(HardwareTriggerReceiver.class)) {
            hardwareReceiverWrapper = registeredReceiver;
        }
    }

    assertNotNull(hardwareReceiverWrapper);

    IntentFilter intentFilter = hardwareReceiverWrapper.getIntentFilter();
    assertEquals(Intent.ACTION_SCREEN_ON, intentFilter.getAction(0));
    assertEquals(Intent.ACTION_SCREEN_OFF, intentFilter.getAction(1));
}
项目:q-mail    文件:MessagingControllerTest.java   
@Before
public void setUp() throws MessagingException {
    ShadowLog.stream = System.out;
    MockitoAnnotations.initMocks(this);
    appContext = ShadowApplication.getInstance().getApplicationContext();

    controller = new MessagingController(appContext, notificationController, contacts, transportProvider);

    configureAccount();
    configureLocalStore();
}
项目:GitHub    文件:DefaultConnectivityMonitorFactoryTest.java   
@Test
public void testReturnsDefaultConnectivityMonitorWhenHasPermission() {
  ShadowApplication.getInstance().grantPermissions("android.permission.ACCESS_NETWORK_STATE");
  ConnectivityMonitor connectivityMonitor = factory.build(RuntimeEnvironment.application,
      mock(ConnectivityMonitor.ConnectivityListener.class));
  assertThat(connectivityMonitor).isInstanceOf(DefaultConnectivityMonitor.class);
}
项目:GitHub    文件:DefaultConnectivityMonitorFactoryTest.java   
@Test
public void testReturnsDefaultConnectivityMonitorWhenHasPermission() {
  ShadowApplication.getInstance().grantPermissions("android.permission.ACCESS_NETWORK_STATE");
  ConnectivityMonitor connectivityMonitor = factory.build(RuntimeEnvironment.application,
      mock(ConnectivityMonitor.ConnectivityListener.class));
  assertThat(connectivityMonitor).isInstanceOf(DefaultConnectivityMonitor.class);
}
项目:JobSchedulerCompat    文件:AlarmSchedulerTest.java   
@Test
public void testScheduleRunsService() {
    scheduler.schedule(job);

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());
}
项目:JobSchedulerCompat    文件:AlarmSchedulerTest.java   
@Test
public void testCancelRunsService() {
    scheduler.cancel(0);

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());
}
项目:JobSchedulerCompat    文件:AlarmSchedulerTest.java   
@Test
public void testCancelAllRunsService() {
    scheduler.cancelAll();

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());
}
项目:JobSchedulerCompat    文件:AlarmSchedulerTest.java   
@Test
public void testJobFinishedRunsService() {
    scheduler.onJobCompleted(0, false);

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());

    scheduler.onJobCompleted(0, true);

    assertEquals(ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName(),
                 AlarmJobService.class.getName());
}
项目:JobSchedulerCompat    文件:AlarmJobServiceTest.java   
@Test
public void testContentTriggerConstraint() {
    jobStore.add(JobStatus.createFromJobInfo(
            JobCreator.create(context, 0, DELAY_MS)
                      .addTriggerContentUri(new JobInfo.TriggerContentUri(Uri.parse("com.doist"), 0))
                      .build(),
            AlarmScheduler.TAG));

    service.startCommand(0, 0);

    assertEquals(ContentObserverService.class.getCanonicalName(),
                 ShadowApplication.getInstance().getNextStartedService().getComponent().getClassName());
}
项目:JobSchedulerCompat    文件:GcmSchedulerTest.java   
private Intent getLastBroadcastIntent() {
    List<Intent> broadcastIntents = ShadowApplication.getInstance().getBroadcastIntents();
    int count = broadcastIntents.size();
    if (count > 0) {
        return broadcastIntents.get(count - 1);
    } else {
        return null;
    }
}
项目:JobSchedulerCompat    文件:ShadowContextImpl.java   
@Implementation
public void removeStickyBroadcast(Intent intent) {
    try {
        ShadowApplication application = ShadowApplication.getInstance();
        Field field = org.robolectric.shadows.ShadowApplication.class.getDeclaredField("stickyIntents");
        field.setAccessible(true);
        @SuppressWarnings("unchecked")
        Map<String, Intent> stickyIntents = (Map<String, Intent>) field.get(application);
        stickyIntents.remove(intent.getAction());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:SpySms    文件:SmsUnitTest.java   
@Test
public void testBroadcastReceiverRegistered() {
    List<ShadowApplication.Wrapper> registeredReceivers = ShadowApplication.getInstance().getRegisteredReceivers();
    assertFalse(registeredReceivers.isEmpty());

    boolean receiverFound = false;
    for (ShadowApplication.Wrapper wrapper : registeredReceivers) {
        if (!receiverFound)
            receiverFound = IncomingSmsReceiver.class.getSimpleName().equals(
                    wrapper.broadcastReceiver.getClass().getSimpleName());
    }

    // False if not found
    Assert.assertTrue(receiverFound);
}
项目:chromium-net-for-android    文件:HttpNegotiateAuthenticatorTest.java   
/**
 * Tests the behavior of {@link HttpNegotiateAuthenticator.GetTokenCallback} when the result it
 * receives contains an intent rather than a token directly.
 */
@Test
public void testGetTokenCallbackWithIntent() {
    String type = "Dummy_Account";
    HttpNegotiateAuthenticator authenticator = createWithoutNative(type);
    RequestData requestData = new RequestData();
    requestData.nativeResultObject = 42;
    requestData.authTokenType = "foo";
    requestData.account = new Account("a", type);
    requestData.accountManager = sMockAccountManager;
    Bundle b = new Bundle();
    b.putParcelable(AccountManager.KEY_INTENT, new Intent());

    authenticator.new GetTokenCallback(requestData).run(makeFuture(b));
    verifyZeroInteractions(sMockAccountManager);

    // Verify that the broadcast receiver is registered
    Intent intent = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
    ShadowApplication shadowApplication = Robolectric.getShadowApplication();
    List<BroadcastReceiver> receivers = shadowApplication.getReceiversForIntent(intent);
    assertThat("There is one registered broadcast receiver", receivers.size(), equalTo(1));

    // Send the intent to the receiver.
    BroadcastReceiver receiver = receivers.get(0);
    receiver.onReceive(Robolectric.getShadowApplication().getApplicationContext(), intent);

    // Verify that the auth token is properly requested from the account manager.
    verify(sMockAccountManager).getAuthToken(
            eq(new Account("a", type)),
            eq("foo"),
            isNull(Bundle.class),
            eq(true),
            any(HttpNegotiateAuthenticator.GetTokenCallback.class),
            any(Handler.class));
}
项目:androidadvanced    文件:BaseTest.java   
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    if (RuntimeEnvironment.application != null) {
        ShadowApplication shadowApp = Shadows.shadowOf(RuntimeEnvironment.application);
        shadowApp.grantPermissions("android.permission.INTERNET");
    }
}
项目:crockpod    文件:AlarmReceiverTest.java   
@Test
public void onReceiveStartsTheAlarmRingingActivityWithExtras() {
    alarmReceiver.onReceive(context, intent);
    ShadowApplication shadowApplication = shadowOf(RuntimeEnvironment.application);
    Intent nextActivity = shadowApplication.peekNextStartedActivity();

    assertEquals(AlarmRingingActivity.class.getName(), nextActivity.getComponent().getClassName());
    assertEquals(alarm.getIntent().getExtras().toString(), nextActivity.getExtras().toString());
}
项目:RNLearn_Project1    文件:ShareModuleTest.java   
@Test
public void testShareDialog() {
  final String title = "Title";
  final String message = "Message";
  final String dialogTitle = "Dialog Title";

  JavaOnlyMap content = new JavaOnlyMap();
  content.putString("title", title);
  content.putString("message", message);

  final SimplePromise promise = new SimplePromise();

  mShareModule.share(content, dialogTitle, promise);

  final Intent chooserIntent = 
    ((ShadowApplication)ShadowExtractor.extract(RuntimeEnvironment.application)).getNextStartedActivity();
  assertNotNull("Dialog was not displayed", chooserIntent);
  assertEquals(Intent.ACTION_CHOOSER, chooserIntent.getAction());
  assertEquals(dialogTitle, chooserIntent.getExtras().get(Intent.EXTRA_TITLE));

  final Intent contentIntent = (Intent)chooserIntent.getExtras().get(Intent.EXTRA_INTENT);
  assertNotNull("Intent was not built correctly", contentIntent);
  assertEquals(Intent.ACTION_SEND, contentIntent.getAction());
  assertEquals(title, contentIntent.getExtras().get(Intent.EXTRA_SUBJECT));
  assertEquals(message, contentIntent.getExtras().get(Intent.EXTRA_TEXT));

  assertEquals(1, promise.getResolved());
}
项目:RNLearn_Project1    文件:ShareModuleTest.java   
@Test
public void testShareDialog() {
  final String title = "Title";
  final String message = "Message";
  final String dialogTitle = "Dialog Title";

  JavaOnlyMap content = new JavaOnlyMap();
  content.putString("title", title);
  content.putString("message", message);

  final SimplePromise promise = new SimplePromise();

  mShareModule.share(content, dialogTitle, promise);

  final Intent chooserIntent = 
    ((ShadowApplication)ShadowExtractor.extract(RuntimeEnvironment.application)).getNextStartedActivity();
  assertNotNull("Dialog was not displayed", chooserIntent);
  assertEquals(Intent.ACTION_CHOOSER, chooserIntent.getAction());
  assertEquals(dialogTitle, chooserIntent.getExtras().get(Intent.EXTRA_TITLE));

  final Intent contentIntent = (Intent)chooserIntent.getExtras().get(Intent.EXTRA_INTENT);
  assertNotNull("Intent was not built correctly", contentIntent);
  assertEquals(Intent.ACTION_SEND, contentIntent.getAction());
  assertEquals(title, contentIntent.getExtras().get(Intent.EXTRA_SUBJECT));
  assertEquals(message, contentIntent.getExtras().get(Intent.EXTRA_TEXT));

  assertEquals(1, promise.getResolved());
}
项目:ello-android    文件:MainActivityTest.java   
@Test
public void registersReceiverForDeviceRegistered() throws Exception {
    List<ShadowApplication.Wrapper> registeredReceivers = ShadowApplication.getInstance().getRegisteredReceivers();

    Assert.assertEquals(false, registeredReceivers.isEmpty());
    Intent intent = new Intent(ElloPreferences.REGISTRATION_COMPLETE);
    ShadowApplication shadowApplication = ShadowApplication.getInstance();
    assertTrue("is registered for REGISTRATION_COMPLETE", shadowApplication.hasReceiverForIntent(intent));
}