org.robolectric.shadows.ShadowApplication Java Examples

The following examples show how to use org.robolectric.shadows.ShadowApplication. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BluetoothCentralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);

    application = ShadowApplication.getInstance();

    bluetoothAdapter = Shadow.extract(ShadowBluetoothLEAdapter.getDefaultAdapter());
    bluetoothAdapter.setEnabled(true);
    bluetoothAdapter.setBluetoothLeScanner(scanner);

    context = application.getApplicationContext();

    // Setup hardware features
    PackageManager packageManager = context.getPackageManager();
    ShadowPackageManager shadowPackageManager = shadowOf(packageManager);
    shadowPackageManager.setSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE, true);

    central = new BluetoothCentral(context, callback, handler);
}
 
Example #2
Source File: BaseBindingGoroTest.java    From goro with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: LocationsGPSUpdaterNoPermissionTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void locationsGPSUpdater_shouldEmitPermissionRequestAndonRequestResultFalse() {
    Application context = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowContext = Shadows.shadowOf(context);
    shadowContext.setSystemService(Context.LOCATION_SERVICE, mockLocationManager);
    LocationsGPSUpdater locationsGPSUpdater = new LocationsGPSUpdater(context);

    doThrow(SecurityException.class)
            .when(mockLocationManager)
            .requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    1000,
                    1,
                    mockLocationListener);

    locationsGPSUpdater.requestLocationUpdates(mockLocationListener, mockRequestUpdatesListener, 1000);

    verify(mockRequestUpdatesListener, times(1)).onRequestResult(false);
    verify(mockErrorListener, times(1)).onError(any());
    verify(mockLocationListener, never()).onLocationChanged(any());
}
 
Example #4
Source File: FragmentsSelectTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setupActivity() {
    Application application = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowApplication = shadowOf(application);
    shadowApplication.grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION);
    Intent intent = new Intent(application, ITagsService.class);
    ITagsService iTagsService = new ITagsService();
    shadowApplication.setComponentNameAndServiceForBindServiceForIntent(
            intent,
            new ComponentName(ITagApplication.class.getPackage().getName(),ITagsService.class.getName()),
            iTagsService.onBind(null)
    );
    mockBluetoothManager = Mockito.mock(BluetoothManager.class);
    ShadowContextImpl shadowContext = Shadow.extract(application.getBaseContext());
    shadowContext.setSystemService(Context.BLUETOOTH_SERVICE, mockBluetoothManager);
}
 
Example #5
Source File: LaunchAnalyzerReceiverTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: RouteFragmentTest.java    From open with GNU General Public License v3.0 6 votes vote down vote up
@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");
}
 
Example #7
Source File: BaseFragmentActivityTest.java    From edx-app-android with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #8
Source File: MainActivityTest.java    From ello-android with MIT License 5 votes vote down vote up
@Test
public void registersReceiverForPushNotifications() throws Exception {
    List<ShadowApplication.Wrapper> registeredReceivers = ShadowApplication.getInstance().getRegisteredReceivers();

    Assert.assertEquals(false, registeredReceivers.isEmpty());

    Intent intent = new Intent(ElloPreferences.PUSH_RECEIVED);
    ShadowApplication shadowApplication = ShadowApplication.getInstance();
    assertTrue("is registered for PUSH_RECEIVED", shadowApplication.hasReceiverForIntent(intent));
}
 
Example #9
Source File: AnalyzerServiceTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Test
public void onStartCommand() throws Exception {
    Intent intent = new Intent(ShadowApplication.getInstance().getApplicationContext(), AnalyzerService.class);
    ShadowApplication.getInstance().startService(intent);

    Intent i = ShadowApplication.getInstance().peekNextStartedService();
    assertEquals(i.getComponent().getClassName(),AnalyzerService.class.getCanonicalName());

}
 
Example #10
Source File: LaunchAnalyzerReceiverTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiverRegistered() {
    List<ShadowApplication.Wrapper> registeredList = ShadowApplication.getInstance().getRegisteredReceivers();
    assertFalse(registeredList.isEmpty());
    boolean found = false;
    for(ShadowApplication.Wrapper wrapper : registeredList) {
        if(wrapper.broadcastReceiver.getClass().getSimpleName().equals(LaunchAnalyzerReceiver.class.getSimpleName())) {
            found = true;
            break;
        }
    }
    assertTrue(found);
}
 
Example #11
Source File: DownloadManagerTest.java    From Android-HttpDownloadManager with Apache License 2.0 5 votes vote down vote up
@Before public void setUp() throws Exception {
  ShadowLog.stream = System.out;
  mockWebServer = new MockWebServer();
  downloadManager = new DownloadManager.Builder().context(
      ShadowApplication.getInstance().getApplicationContext()).build();
  String filePath =
      ShadowEnvironment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
          + File.separator
          + "download.apk";

  request = new DownloadRequest.Builder().url(mockWebServer.url("/").toString())
      .destinationFilePath(filePath)
      .build();
}
 
Example #12
Source File: UTest.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@Test
@Config(sdk = 21)
public void testHasWriteSecureSettingsPermissionVersionBelowMarshmallow() {
    Application application = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowApplication = Shadows.shadowOf(application);
    shadowApplication.grantPermissions(Manifest.permission.WRITE_SECURE_SETTINGS);
    assertFalse(U.hasWriteSecureSettingsPermission(context));
}
 
Example #13
Source File: UTest.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@Test
public void testHasWriteSecureSettingsPermissionForMarshmallowAndAboveVersion() {
    assertFalse(U.hasWriteSecureSettingsPermission(context));
    Application application = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowApplication = Shadows.shadowOf(application);
    shadowApplication.grantPermissions(Manifest.permission.WRITE_SECURE_SETTINGS);
    assertTrue(U.hasWriteSecureSettingsPermission(context));
}
 
Example #14
Source File: RegistrationIntentServiceTest.java    From ello-android with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    serviceIntent = new Intent(RuntimeEnvironment.application, RegistrationIntentService.class);

    ((TestNetComponent)((TestElloApp) RuntimeEnvironment.application).getNetComponent()).inject(this);
    ShadowApplication.getInstance().startService(serviceIntent);

    ServiceController<RegistrationIntentService> serviceController = Robolectric.buildService(RegistrationIntentService.class);
    serviceController.attach()
            .create()
            .startCommand(0, 1);
    service = serviceController.get();
}
 
Example #15
Source File: MainActivityTest.java    From ello-android with MIT License 5 votes vote down vote up
@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));
}
 
Example #16
Source File: AbstractDbTest.java    From financisto with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    Application application = ApplicationProvider.getApplicationContext();
    ShadowApplication app = Shadows.shadowOf(application);
    app.grantPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);

    context = application;
    dbHelper = new DatabaseHelper(context);
    db = new TestDatabaseAdapter(context, dbHelper);
    db.open();
}
 
Example #17
Source File: ShareModuleTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@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());
}
 
Example #18
Source File: SDK21IntTest.java    From itag with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setupActivity() {
    Application application = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowApplication = shadowOf(application);
    shadowApplication.grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION);
    Intent intent = new Intent(application, ITagsService.class);
    ITagsService iTagsService = new ITagsService();
    shadowApplication.setComponentNameAndServiceForBindServiceForIntent(
            intent,
            new ComponentName(ITagApplication.class.getPackage().getName(),ITagsService.class.getName()),
            iTagsService.onBind(null)
    );
    mainActivity = Robolectric.setupActivity(MainActivity.class);
}
 
Example #19
Source File: FixesTest.java    From itag with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setupActivity() {
    Application application = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowApplication = shadowOf(application);
    shadowApplication.grantPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION});
    Intent intent = new Intent(application, ITagsService.class);
    ITagsService iTagsService = new ITagsService();
    shadowApplication.setComponentNameAndServiceForBindServiceForIntent(
            intent,
            new ComponentName(ITagsService.class.getPackage().getName(),ITagsService.class.getName()),
            iTagsService.onBind(null)
    );
    mainActivity = Robolectric.setupActivity(MainActivity.class);
}
 
Example #20
Source File: LocationsGPSUpdaterNoPermissionTest.java    From itag with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void shadowContext_shouldProvideMockedSystemService() {
    Application context = ApplicationProvider.getApplicationContext();
    ShadowApplication shadowContext = Shadows.shadowOf(context);
    shadowContext.setSystemService(Context.LOCATION_SERVICE, mockLocationManager);

    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    assertThat(manager).isEqualTo(mockLocationManager);
}
 
Example #21
Source File: SalvageTestRunner.java    From salvage with Apache License 2.0 4 votes vote down vote up
@Override public void setupApplicationState(Method testMethod) {
  Robolectric.application = ShadowApplication.bind(createApplication(), null, null);
}
 
Example #22
Source File: ItemActivityTest.java    From materialistic with Apache License 2.0 4 votes vote down vote up
@Config(shadows = ShadowRecyclerView.class)
@Test
public void testScrollToTop() {
    Intent intent = new Intent();
    intent.putExtra(ItemActivity.EXTRA_ITEM, new TestItem() {
        @NonNull
        @Override
        public String getType() {
            return STORY_TYPE;
        }

        @Override
        public String getId() {
            return "1";
        }

        @Override
        public boolean isStoryType() {
            return true;
        }

        @Override
        public int getKidCount() {
            return 10;
        }

        @Override
        public String getUrl() {
            return "http://example.com";
        }
    });
    controller = Robolectric.buildActivity(ItemActivity.class, intent);
    controller.create().start().resume();
    activity = controller.get();
    // see https://github.com/robolectric/robolectric/issues/1326
    ShadowLooper.pauseMainLooper();
    controller.visible();
    ShadowApplication.getInstance().getForegroundThreadScheduler().advanceToLastPostedRunnable();
    RecyclerView recyclerView = activity.findViewById(R.id.recycler_view);
    recyclerView.smoothScrollToPosition(1);
    assertThat(customShadowOf(recyclerView).getScrollPosition()).isEqualTo(1);
    TabLayout tabLayout = activity.findViewById(R.id.tab_layout);
    assertThat(tabLayout.getTabCount()).isEqualTo(2);
    tabLayout.getTabAt(1).select();
    tabLayout.getTabAt(0).select();
    tabLayout.getTabAt(0).select();
    assertThat(customShadowOf(recyclerView).getScrollPosition()).isEqualTo(0);
}
 
Example #23
Source File: ItemActivityTest.java    From materialistic with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
@Test
public void testShare() {
    TestApplication.addResolver(new Intent(Intent.ACTION_SEND));
    Intent intent = new Intent();
    intent.putExtra(ItemActivity.EXTRA_ITEM, new TestItem() {
        @NonNull
        @Override
        public String getType() {
            return STORY_TYPE;
        }

        @Override
        public String getUrl() {
            return "http://example.com";
        }

        @Override
        public boolean isStoryType() {
            return true;
        }

        @Override
        public String getId() {
            return "1";
        }
    });
    controller = Robolectric.buildActivity(ItemActivity.class, intent);
    controller.create().start().resume();
    activity = controller.get();

    // inflate menu, see https://github.com/robolectric/robolectric/issues/1326
    ShadowLooper.pauseMainLooper();
    controller.visible();
    ShadowApplication.getInstance().getForegroundThreadScheduler().advanceToLastPostedRunnable();

    // share article
    shadowOf(activity).clickMenuItem(R.id.menu_share);
    shadowOf(ShadowPopupMenu.getLatestPopupMenu())
            .getOnMenuItemClickListener()
            .onMenuItemClick(new RoboMenuItem(R.id.menu_article));
    ShadowApplication.getInstance().getForegroundThreadScheduler().advanceToLastPostedRunnable();
    Intent actual = shadowOf(activity).getNextStartedActivity();
    assertThat(actual)
            .hasAction(Intent.ACTION_SEND);

    // share item
    shadowOf(activity).clickMenuItem(R.id.menu_share);
    shadowOf(ShadowPopupMenu.getLatestPopupMenu())
            .getOnMenuItemClickListener()
            .onMenuItemClick(new RoboMenuItem(R.id.menu_comments));
    ShadowApplication.getInstance().getForegroundThreadScheduler().advanceToLastPostedRunnable();
    actual = shadowOf(activity).getNextStartedActivity();
    assertThat(actual)
            .hasAction(Intent.ACTION_SEND);
}
 
Example #24
Source File: ItemActivityTest.java    From materialistic with Apache License 2.0 4 votes vote down vote up
@SuppressLint("NewApi")
@Test
public void testOptionExternal() {
    ShadowPackageManager packageManager = shadowOf(RuntimeEnvironment.application.getPackageManager());
    packageManager.addResolveInfoForIntent(
            new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://example.com")),
            ShadowResolveInfo.newResolveInfo("label", "com.android.chrome", "DefaultActivity"));
    packageManager.addResolveInfoForIntent(
            new Intent(Intent.ACTION_VIEW,
                    Uri.parse(String.format(HackerNewsClient.WEB_ITEM_PATH, "1"))),
            ShadowResolveInfo.newResolveInfo("label", "com.android.chrome", "DefaultActivity"));
    Intent intent = new Intent();
    intent.putExtra(ItemActivity.EXTRA_ITEM, new TestItem() {
        @NonNull
        @Override
        public String getType() {
            return STORY_TYPE;
        }

        @Override
        public String getUrl() {
            return "http://example.com";
        }

        @Override
        public boolean isStoryType() {
            return true;
        }

        @Override
        public String getId() {
            return "1";
        }
    });
    controller = Robolectric.buildActivity(ItemActivity.class, intent);
    controller.create().start().resume();
    activity = controller.get();

    // inflate menu, see https://github.com/robolectric/robolectric/issues/1326
    ShadowLooper.pauseMainLooper();
    controller.visible();
    ShadowApplication.getInstance().getForegroundThreadScheduler().advanceToLastPostedRunnable();

    // open article
    shadowOf(activity).clickMenuItem(R.id.menu_external);
    shadowOf(ShadowPopupMenu.getLatestPopupMenu())
            .getOnMenuItemClickListener()
            .onMenuItemClick(new RoboMenuItem(R.id.menu_article));
    ShadowApplication.getInstance().getForegroundThreadScheduler().advanceToLastPostedRunnable();
    assertThat(shadowOf(activity).getNextStartedActivity()).hasAction(Intent.ACTION_VIEW);

    // open item
    shadowOf(activity).clickMenuItem(R.id.menu_external);
    shadowOf(ShadowPopupMenu.getLatestPopupMenu())
            .getOnMenuItemClickListener()
            .onMenuItemClick(new RoboMenuItem(R.id.menu_comments));
    ShadowApplication.getInstance().getForegroundThreadScheduler().advanceToLastPostedRunnable();
    assertThat(shadowOf(activity).getNextStartedActivity()).hasAction(Intent.ACTION_VIEW);
}
 
Example #25
Source File: TestApplication.java    From materialistic with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeTest(Method method) {
    Preferences.sReleaseNotesSeen = true;
    ShadowApplication.getInstance().declareActionUnbindable("com.google.android.gms.analytics.service.START");
}
 
Example #26
Source File: ServiceStub.java    From android-easy-checkout with Apache License 2.0 4 votes vote down vote up
public void setServiceForBinding(final Bundle stubBundle) {
    ShadowApplication shadowApplication = shadowOf(RuntimeEnvironment.application);
    IInAppBillingService.Stub stub = create(stubBundle);
    ComponentName cn = mock(ComponentName.class);
    shadowApplication.setComponentNameAndServiceForBindService(cn, stub);
}
 
Example #27
Source File: ServiceStub.java    From android-easy-checkout with Apache License 2.0 4 votes vote down vote up
public void setServiceForBinding(final Bundle stubBundle) {
    ShadowApplication shadowApplication = shadowOf(RuntimeEnvironment.application);
    IInAppBillingService.Stub stub = create(stubBundle);
    ComponentName cn = mock(ComponentName.class);
    shadowApplication.setComponentNameAndServiceForBindService(cn, stub);
}
 
Example #28
Source File: MyReceiverTest.java    From Awesome-WanAndroid with Apache License 2.0 4 votes vote down vote up
@Test
public void registerReceiver() {
    ShadowApplication application = ShadowApplication.getInstance();
    Assert.assertNotNull(application.hasReceiverForIntent(intent));
}
 
Example #29
Source File: ShadowBluetoothLEAdapter.java    From blessed-android with MIT License 4 votes vote down vote up
@Implementation
public static BluetoothAdapter getDefaultAdapter() {
    return (BluetoothAdapter) ShadowApplication.getInstance().getBluetoothAdapter();
}