org.robolectric.Shadows Java Examples

The following examples show how to use org.robolectric.Shadows. 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: ComponentWarmerTest.java    From litho with Apache License 2.0 7 votes vote down vote up
@Before
public void setup() {
  mContext = new ComponentContext(getApplicationContext());
  mComponentRenderInfo =
      ComponentRenderInfo.create()
          .component(SimpleMountSpecTester.create(mContext).build())
          .customAttribute(ComponentWarmer.COMPONENT_WARMER_TAG, "tag1")
          .build();
  mPrepareComponentRenderInfo =
      ComponentRenderInfo.create()
          .component(SimpleMountSpecTester.create(mContext).build())
          .build();
  mLayoutThreadShadowLooper =
      Shadows.shadowOf(
          (Looper) Whitebox.invokeMethod(ComponentTree.class, "getDefaultLayoutThreadLooper"));
  mWidthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY);
  mHeightSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY);
}
 
Example #2
Source File: StateUpdatesWithReconciliationTest.java    From litho with Apache License 2.0 7 votes vote down vote up
public void before(Component component) {
  ComponentsConfiguration.isEndToEndTestRun = true;

  NodeConfig.sInternalNodeFactory =
      new NodeConfig.InternalNodeFactory() {
        @Override
        public InternalNode create(ComponentContext c) {
          return spy(new DefaultInternalNode(c));
        }
      };
  mComponentsLogger = new TestComponentsLogger();
  mContext = new ComponentContext(getApplicationContext(), mLogTag, mComponentsLogger);
  mLayoutThreadShadowLooper =
      Shadows.shadowOf(
          (Looper) Whitebox.invokeMethod(ComponentTree.class, "getDefaultLayoutThreadLooper"));
  mRootComponent = component != null ? component : new DummyComponent();
  mLithoView = new LithoView(mContext);
  mComponentTree =
      spy(ComponentTree.create(mContext, mRootComponent).isReconciliationEnabled(true).build());

  mLithoView.setComponentTree(mComponentTree);
  mLithoView.onAttachedToWindow();

  ComponentTestHelper.measureAndLayout(mLithoView);
}
 
Example #3
Source File: ComponentTreeNewLayoutStateReadyListenerTest.java    From litho with Apache License 2.0 7 votes vote down vote up
@Before
public void setup() throws Exception {
  mContext = new ComponentContext(getApplicationContext());
  mComponent = SimpleMountSpecTester.create(mContext).build();
  mComponentTree = create(mContext, mComponent).build();

  mLayoutThreadShadowLooper =
      Shadows.shadowOf(
          (Looper) Whitebox.invokeMethod(ComponentTree.class, "getDefaultLayoutThreadLooper"));

  mWidthSpec = makeSizeSpec(39, EXACTLY);
  mWidthSpec2 = makeSizeSpec(40, EXACTLY);
  mHeightSpec = makeSizeSpec(41, EXACTLY);
  mHeightSpec2 = makeSizeSpec(42, EXACTLY);

  mListener = mock(ComponentTree.NewLayoutStateReadyListener.class);
}
 
Example #4
Source File: NestedComponentStateUpdatesWithReconciliationTest.java    From litho with Apache License 2.0 7 votes vote down vote up
@Before
public void before() {
  ComponentsConfiguration.isEndToEndTestRun = true;

  NodeConfig.sInternalNodeFactory =
      new NodeConfig.InternalNodeFactory() {
        @Override
        public InternalNode create(ComponentContext c) {
          DefaultInternalNode node = spy(new DefaultInternalNode(c));
          node.getYogaNode().setData(node);
          return node;
        }
      };
  mComponentsLogger = new TestComponentsLogger();
  c = new ComponentContext(getApplicationContext(), mLogTag, mComponentsLogger);
  mLayoutThreadShadowLooper =
      Shadows.shadowOf(
          (Looper) Whitebox.invokeMethod(ComponentTree.class, "getDefaultLayoutThreadLooper"));
}
 
Example #5
Source File: IntentsTest.java    From droidconat-2016 with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_false_when_nothing_on_the_device_can_open_the_uri() {
    // Given
    String url = "http://www.google.com";
    RobolectricPackageManager rpm = (RobolectricPackageManager) RuntimeEnvironment.application.getPackageManager();
    rpm.addResolveInfoForIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), (ResolveInfo) null);

    // When
    boolean result = Intents.startUri(activity, url);

    // Then
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    Intent startedIntent = shadowActivity.getNextStartedActivity();

    assertThat(result).isFalse();
    assertThat(startedIntent).isNull();
}
 
Example #6
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 #7
Source File: TestActivityTest.java    From Awesome-WanAndroid with Apache License 2.0 6 votes vote down vote up
@Test
public void showToast() {
    Toast latestToast = ShadowToast.getLatestToast();
    Assert.assertNull(latestToast);

    Button button = (Button) mTestActivity.findViewById(R.id.button2);
    button.performClick();

    latestToast = ShadowToast.getLatestToast();
    Assert.assertNotNull(latestToast);

    ShadowToast shadowToast = Shadows.shadowOf(latestToast);
    ShadowLog.d("toast_time", shadowToast.getDuration() + "");
    Assert.assertEquals(Toast.LENGTH_SHORT, shadowToast.getDuration());
    Assert.assertEquals("hahaha", ShadowToast.getTextOfLatestToast());
}
 
Example #8
Source File: UploadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyUpload() throws Exception {
  System.out.println("Starting test emptyUpload.");

  MockConnectionFactory factory = NetworkLayerMock.ensureNetworkMock("emptyUpload", true);

  String filename = TEST_ASSET_ROOT + "empty.dat";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<StringBuilder> task = TestUploadHelper.fileUpload(sourceFile, "empty.dat");

  TestUtil.await(task, 5, TimeUnit.SECONDS);

  factory.verifyOldMock();
  TestUtil.verifyTaskStateChanges("emptyUpload", task.getResult().toString());
}
 
Example #9
Source File: LocationsGPSUpdaterTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void locationsGPSUpdater_shouldEmitNotificationsOnLocationUpdates() {
    Application context = ApplicationProvider.getApplicationContext();
    LocationsGPSUpdater locationsGPSUpdater = new LocationsGPSUpdater(context);
    LocationManager manager =
            (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    ShadowLocationManager shadowLocationManager = Shadows.shadowOf(manager);


    locationsGPSUpdater.requestLocationUpdates(mockLocationListener, mockRequestUpdatesListener, 1000);
    verify(mockLocationListener, never()).onLocationChanged(any());

    Location location = new Location(LocationManager.GPS_PROVIDER);
    shadowLocationManager.simulateLocation(location);
    verify(mockLocationListener).onLocationChanged(any());
}
 
Example #10
Source File: RobolectricUtils.java    From android-browser-helper with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures intents with {@link CustomTabsService#ACTION_CUSTOM_TABS_CONNECTION} resolve to a
 * Service with given categories
 */
public static void installCustomTabsService(String providerPackage, List<String> categories) {
    Intent intent = new Intent()
            .setAction(CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION)
            .setPackage(providerPackage);

    IntentFilter filter = new IntentFilter();
    for (String category : categories) {
        filter.addCategory(category);
    }
    ResolveInfo resolveInfo = new ResolveInfo();
    resolveInfo.filter = filter;

    ShadowPackageManager manager = Shadows.shadowOf(RuntimeEnvironment.application
            .getPackageManager());
    manager.addResolveInfoForIntent(intent, resolveInfo);
}
 
Example #11
Source File: IntentsTest.java    From droidconat-2016 with Apache License 2.0 6 votes vote down vote up
@Test
public void should_start_external_uri() {
    // Given
    String url = "http://www.google.com";
    RobolectricPackageManager rpm = (RobolectricPackageManager) RuntimeEnvironment.application.getPackageManager();
    rpm.addResolveInfoForIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), ShadowResolveInfo.newResolveInfo("", "", ""));

    // When
    Intents.startExternalUrl(activity, url);

    // Then
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    Intent startedIntent = shadowActivity.getNextStartedActivity();

    assertThat(startedIntent.getAction()).isEqualTo(Intent.ACTION_VIEW);
    assertThat(startedIntent.getData().toString()).isEqualTo(url);
}
 
Example #12
Source File: UploadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void fileUploadNoRecovery() throws Exception {
  System.out.println("Starting test fileUploadNoRecovery.");

  MockConnectionFactory factory =
      NetworkLayerMock.ensureNetworkMock("fileUploadNoRecovery", false);

  String filename = TEST_ASSET_ROOT + "flubbertest.jpg";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<StringBuilder> task = TestUploadHelper.fileUpload(sourceFile, "flubbertest.jpg");

  TestUtil.await(task, 5, TimeUnit.SECONDS);

  factory.verifyOldMock();
  TestUtil.verifyTaskStateChanges("fileUploadNoRecovery", task.getResult().toString());
}
 
Example #13
Source File: UploadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void fileUploadRecovery() throws Exception {
  System.out.println("Starting test fileUploadRecovery.");

  MockConnectionFactory factory = NetworkLayerMock.ensureNetworkMock("fileUploadRecovery", false);

  String filename = TEST_ASSET_ROOT + "flubbertest.jpg";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<StringBuilder> task = TestUploadHelper.fileUpload(sourceFile, "flubbertest.jpg");

  TestUtil.await(task, 5, TimeUnit.SECONDS);

  factory.verifyOldMock();
  TestUtil.verifyTaskStateChanges("fileUploadRecovery", task.getResult().toString());
}
 
Example #14
Source File: UploadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void fileUploadWithQueueCancel() throws Exception {
  System.out.println("Starting test fileUploadWithQueueCancel.");

  ResumableUploadCancelRequest.cancelCalled = false;

  final StringBuilder taskOutput = new StringBuilder();
  NetworkLayerMock.ensureNetworkMock("fileUploadWithPauseCancel", true);

  String filename = TEST_ASSET_ROOT + "image.jpg";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<Void> task = TestUploadHelper.fileUploadQueuedCancel(taskOutput, sourceFile);

  TestUtil.await(task, 2, TimeUnit.SECONDS);

  TestUtil.verifyTaskStateChanges("fileUploadWithQueueCancel", taskOutput.toString());
  Assert.assertFalse(ResumableUploadCancelRequest.cancelCalled);
}
 
Example #15
Source File: UploadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void fileUploadWithPauseResume() throws Exception {
  System.out.println("Starting test fileUploadWithPauseResume.");

  MockConnectionFactory factory =
      NetworkLayerMock.ensureNetworkMock("fileUploadWithPauseResume", true);

  factory.setPauseRecord(4);

  String filename = TEST_ASSET_ROOT + "image.jpg";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<StringBuilder> task =
      TestUploadHelper.fileUploadWithPauseResume(factory.getSemaphore(), sourceFile);

  // This is 20 seconds due to a fairness bug where resumed tasks can be put at the end.
  TestUtil.await(task, 20, TimeUnit.SECONDS);

  TestUtil.verifyTaskStateChanges("fileUploadWithPauseResume", task.getResult().toString());
}
 
Example #16
Source File: TestActivityTest.java    From Awesome-WanAndroid with Apache License 2.0 6 votes vote down vote up
@Test
public void showDialog() {
    AlertDialog latestAlertDialog = ShadowAlertDialog.getLatestAlertDialog();
    Assert.assertNull(latestAlertDialog);

    Button button = (Button) mTestActivity.findViewById(R.id.button3);
    button.performClick();

    latestAlertDialog = ShadowAlertDialog.getLatestAlertDialog();
    Assert.assertNotNull(latestAlertDialog);

    ShadowAlertDialog shadowAlertDialog = Shadows.shadowOf(latestAlertDialog);
    Assert.assertEquals("Dialog", shadowAlertDialog.getTitle());
    ShadowLog.d("dialog_tag", (String) shadowAlertDialog.getMessage());
    Assert.assertEquals("showDialog", shadowAlertDialog.getMessage());
}
 
Example #17
Source File: ViewControllerTest.java    From react-native-navigation with MIT License 6 votes vote down vote up
@Test
public void onDestroy_RemovesGlobalLayoutListener() throws Exception {
    new SimpleViewController(activity, childRegistry, "ensureNotNull", new Options()).destroy();

    ViewController spy = spy(uut);
    View view = spy.getView();
    Shadows.shadowOf(view).setMyParent(mock(ViewParent.class));

    spy.destroy();

    Assertions.assertThat(view).isShown();
    view.getViewTreeObserver().dispatchOnGlobalLayout();
    verify(spy, times(0)).onViewAppeared();
    verify(spy, times(0)).onViewDisappear();

    Field field = ViewController.class.getDeclaredField("view");
    field.setAccessible(true);
    assertThat(field.get(spy)).isNull();
}
 
Example #18
Source File: ViewPredicates.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to extract the description of a drawn view from a canvas
 *
 * <p>Since Robolectric can screw up {@link View#draw}, this uses reflection to call {@link
 * View#onDraw} and give you a canvas that has all the information drawn into it. This is useful
 * for asserting some view draws something specific to a canvas.
 *
 * @param view the view to draw
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String getDrawnViewDescription(View view) {
  final Canvas canvas = new Canvas();
  view.draw(canvas);
  final ShadowCanvas shadowCanvas = Shadows.shadowOf(canvas);
  if (!shadowCanvas.getDescription().isEmpty()) {
    return shadowCanvas.getDescription();
  }

  try {
    Method onDraw = getOnDrawMethod(view.getClass());

    if (onDraw == null) {
      throw new RuntimeException(
          view.getClass().getCanonicalName()
              + " has no implementation of View.onDraw(), which should be impossible");
    }

    onDraw.invoke(view, canvas);
    final ShadowCanvas shadowCanvas2 = Shadows.shadowOf(canvas);
    return shadowCanvas2.getDescription();
  } catch (IllegalAccessException | InvocationTargetException e) {
    throw new RuntimeException(e);
  }
}
 
Example #19
Source File: ComponentQueries.java    From litho with Apache License 2.0 6 votes vote down vote up
private static boolean hasDrawable(Drawable containingDrawable, Drawable drawable) {
  while (containingDrawable instanceof MatrixDrawable) {
    containingDrawable = ((MatrixDrawable) containingDrawable).getMountedDrawable();
  }

  final String drawnDrawableDescription = ViewPredicates.getDrawnDrawableDescription(drawable);
  if (!drawnDrawableDescription.isEmpty()) {
    return ViewPredicates.getDrawnDrawableDescription(containingDrawable)
        .contains(drawnDrawableDescription);
  }

  // Robolectric 3.X provides a shadow implementation of equals() for Drawables, but it only
  // checks that the bounds are equal, which is a pretty weak assertion. This buggy equals()
  // implementation was removed in Robolectric 4.0, and Android Drawable does not implement
  // equals().

  // For Drawables created from a resource we can compare the resource ID they were created with.
  int containingDrawableResId = Shadows.shadowOf(containingDrawable).getCreatedFromResId();
  int drawableResId = Shadows.shadowOf(drawable).getCreatedFromResId();
  if (drawableResId != View.NO_ID && containingDrawableResId == drawableResId) {
    return true;
  }

  // Otherwise we cannot meaningfully compare them. Fall back to pointer equality.
  return containingDrawable == drawable;
}
 
Example #20
Source File: UTest.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
@Test
public void testHasFreeformSupportWithFreeformEnabledAndNMR1AboveVersion() {
    PowerMockito.spy(U.class);
    when(U.canEnableFreeform()).thenReturn(true);
    assertFalse(U.hasFreeformSupport(context));
    // Case 1, system has feature freeform.
    PackageManager packageManager = context.getPackageManager();
    ShadowPackageManager shadowPackageManager = Shadows.shadowOf(packageManager);
    shadowPackageManager
            .setSystemFeature(PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT, true);
    assertTrue(U.hasFreeformSupport(context));
    shadowPackageManager
            .setSystemFeature(PackageManager.FEATURE_FREEFORM_WINDOW_MANAGEMENT, false);
    // Case 2, enable_freeform_support in Settings.Global is not 0
    Settings.Global.putInt(context.getContentResolver(), "enable_freeform_support", 1);
    assertTrue(U.hasFreeformSupport(context));
    Settings.Global.putInt(context.getContentResolver(), "enable_freeform_support", 0);
}
 
Example #21
Source File: UTest.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
private void testShowPermissionDialog(boolean hasAndroidTVSettings,
                                      String message,
                                      int buttonTextResId) throws Exception {
    RunnableHooker onError = new RunnableHooker();
    RunnableHooker onFinish = new RunnableHooker();
    PowerMockito.spy(U.class);
    when(U.class, "hasAndroidTVSettings", context).thenReturn(hasAndroidTVSettings);
    AlertDialog dialog = U.showPermissionDialog(context, new Callbacks(onError, onFinish));
    ShadowAlertDialog shadowDialog = Shadows.shadowOf(dialog);
    Resources resources = context.getResources();
    assertEquals(
            resources.getString(R.string.tb_permission_dialog_title),
            shadowDialog.getTitle()
    );
    assertEquals(message, shadowDialog.getMessage());
    Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
    assertEquals(resources.getString(buttonTextResId), positiveButton.getText());
    assertFalse(shadowDialog.isCancelable());
    positiveButton.performClick();
    assertTrue(onFinish.hasRun());
    assertFalse(onError.hasRun());
}
 
Example #22
Source File: IntentsTest.java    From droidconat-2016 with Apache License 2.0 6 votes vote down vote up
@Test
public void should_start_url_intent() {
    // Given
    String url = "geo:22.5430883,114.1043205";
    RobolectricPackageManager rpm = (RobolectricPackageManager) RuntimeEnvironment.application.getPackageManager();
    rpm.addResolveInfoForIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), ShadowResolveInfo.newResolveInfo("", "", ""));

    // When
    boolean result = Intents.startUri(activity, url);

    // Then
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    Intent startedIntent = shadowActivity.getNextStartedActivity();

    assertThat(result).isTrue();
    assertThat(startedIntent.getAction()).isEqualTo(Intent.ACTION_VIEW);
    assertThat(startedIntent.getData().toString()).isEqualTo(url);
}
 
Example #23
Source File: DemandFetcherTest.java    From prebid-mobile-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testBaseConditions() throws Exception {
    PublisherAdRequest.Builder builder = new PublisherAdRequest.Builder();
    PublisherAdRequest request = builder.build();
    DemandFetcher demandFetcher = new DemandFetcher(request);
    demandFetcher.setPeriodMillis(0);
    HashSet<AdSize> sizes = new HashSet<>();
    sizes.add(new AdSize(300, 250));
    RequestParams requestParams = new RequestParams("12345", AdType.BANNER, sizes);
    demandFetcher.setRequestParams(requestParams);
    assertEquals(DemandFetcher.STATE.STOPPED, FieldUtils.readField(demandFetcher, "state", true));
    demandFetcher.start();
    assertEquals(DemandFetcher.STATE.RUNNING, FieldUtils.readField(demandFetcher, "state", true));
    ShadowLooper fetcherLooper = Shadows.shadowOf(demandFetcher.getHandler().getLooper());
    fetcherLooper.runOneTask();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    demandFetcher.destroy();
    assertEquals(DemandFetcher.STATE.DESTROYED, FieldUtils.readField(demandFetcher, "state", true));
}
 
Example #24
Source File: QueryResponseSenderTest.java    From OpenYOLO-Android with Apache License 2.0 6 votes vote down vote up
private void checkBroadcastResponse(ByteString expectedResponseBytes)
        throws InvalidProtocolBufferException {
    List<Intent> broadcasts =
            Shadows.shadowOf(RuntimeEnvironment.application).getBroadcastIntents();

    assertThat(broadcasts.size()).isEqualTo(1);
    Intent broadcastIntent = broadcasts.get(0);

    assertThat(broadcastIntent.getAction())
            .isEqualTo("example:0000000000000080");
    assertThat(broadcastIntent.getCategories()).containsExactly(QueryUtil.BBQ_CATEGORY);
    assertThat(broadcastIntent.getPackage()).isEqualTo(mQuery.getRequestingApp());
    assertThat(broadcastIntent.getByteArrayExtra(QueryUtil.EXTRA_RESPONSE_MESSAGE)).isNotNull();

    byte[] responseBytes = broadcastIntent.getByteArrayExtra(QueryUtil.EXTRA_RESPONSE_MESSAGE);
    BroadcastQueryResponse response = BroadcastQueryResponse.parseFrom(responseBytes);

    assertThat(response.getRequestId()).isEqualTo(mQuery.getRequestId());
    assertThat(response.getResponseId()).isEqualTo(mQuery.getResponseId());
    assertThat(response.getResponseMessage()).isEqualTo(expectedResponseBytes);
}
 
Example #25
Source File: UploadTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void fileUpload() throws Exception {
  System.out.println("Starting test fileUpload.");

  MockConnectionFactory factory = NetworkLayerMock.ensureNetworkMock("fileUpload", true);

  String filename = TEST_ASSET_ROOT + "image.jpg";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<StringBuilder> task = TestUploadHelper.fileUpload(sourceFile, "image.jpg");

  TestUtil.await(task, 5, TimeUnit.SECONDS);

  factory.verifyOldMock();
  TestUtil.verifyTaskStateChanges("fileUpload", task.getResult().toString());
}
 
Example #26
Source File: ViewControllerTest.java    From react-native-navigation with MIT License 5 votes vote down vote up
@Test
public void onDisappear_WhenNotShown_AfterOnAppearWasCalled() {
    ViewController spy = spy(uut);
    Shadows.shadowOf(spy.getView()).setMyParent(mock(ViewParent.class));
    Assertions.assertThat(spy.getView()).isShown();
    spy.getView().getViewTreeObserver().dispatchOnGlobalLayout();
    verify(spy, times(1)).onViewAppeared();
    verify(spy, times(0)).onViewDisappear();

    spy.getView().setVisibility(View.GONE);
    spy.getView().getViewTreeObserver().dispatchOnGlobalLayout();
    Assertions.assertThat(spy.getView()).isNotShown();
    verify(spy, times(1)).onViewDisappear();
}
 
Example #27
Source File: GetPurchasesTest.java    From android-easy-checkout with Apache License 2.0 5 votes vote down vote up
@Test
public void bindServiceError() throws InterruptedException, RemoteException, BillingException {
    final CountDownLatch latch = new CountDownLatch(1);

    BillingContext context = mDataConverter.newBillingContext(mock(Context.class));
    mProcessor = new BillingProcessor(context, new PurchaseHandler() {
        @Override
        public void call(PurchaseResponse response) {
            throw new IllegalStateException();
        }
    });
    mWorkHandler = mProcessor.getWorkHandler();

    mProcessor.getPurchases(PurchaseType.IN_APP, new PurchasesHandler() {
        @Override
        public void onSuccess(Purchases purchases) {
            throw new IllegalStateException();
        }

        @Override
        public void onError(BillingException e) {
            assertThat(e.getErrorCode()).isEqualTo(Constants.ERROR_BIND_SERVICE_FAILED_EXCEPTION);
            assertThat(e.getMessage()).isEqualTo(Constants.ERROR_MSG_BIND_SERVICE_FAILED);
            latch.countDown();
        }
    });
    Shadows.shadowOf(mWorkHandler.getLooper()).getScheduler().advanceToNextPostedRunnable();

    latch.await(15, TimeUnit.SECONDS);
}
 
Example #28
Source File: ViewControllerTest.java    From react-native-navigation with MIT License 5 votes vote down vote up
@Test
public void onAppear_WhenShown() {
    ViewController spy = spy(uut);
    spy.getView().getViewTreeObserver().dispatchOnGlobalLayout();
    Assertions.assertThat(spy.getView()).isNotShown();
    verify(spy, times(0)).onViewAppeared();

    Shadows.shadowOf(spy.getView()).setMyParent(mock(ViewParent.class));
    spy.getView().getViewTreeObserver().dispatchOnGlobalLayout();
    Assertions.assertThat(spy.getView()).isShown();

    verify(spy, times(1)).onViewAppeared();
}
 
Example #29
Source File: WXTimerModuleTest.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  WXSDKEngine.initialize(RuntimeEnvironment.application, new InitConfig.Builder().build());
  WXBridgeManager bridge = Mockito.mock(WXBridgeManager.class);
  when(bridge.getJSLooper()).thenReturn(new WXThread("js").getLooper());
  WXBridgeManagerTest.setBridgeManager(bridge);

  module = Mockito.spy(new WXTimerModule());
  module.mWXSDKInstance = WXSDKInstanceTest.createInstance();
  Handler handler = new Handler(WXBridgeManager.getInstance().getJSLooper(), module);
  mLooper = Shadows.shadowOf(handler.getLooper());
  module.setHandler(handler);
}
 
Example #30
Source File: TrafficStatsNetworkBytesCollectorTest.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Test
public void testBroadcastNetworkChanges() throws Exception {
  ShadowTrafficStats.setUidRxBytes(10000);
  ShadowTrafficStats.setUidTxBytes(20000);

  TrafficStatsNetworkBytesCollector collector =
      new TrafficStatsNetworkBytesCollector(RuntimeEnvironment.application);
  assertThat(collector.getTotalBytes(mBytes)).isTrue();

  ShadowTrafficStats.setUidRxBytes(11000);
  ShadowTrafficStats.setUidTxBytes(22000);

  ConnectivityManager connectivityManager =
      (ConnectivityManager)
          RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE);
  ShadowConnectivityManager shadowConnectivityManager = Shadows.shadowOf(connectivityManager);
  NetworkInfo networkInfo =
      ShadowNetworkInfo.newInstance(null, ConnectivityManager.TYPE_WIFI, 0, true, true);
  shadowConnectivityManager.setActiveNetworkInfo(networkInfo);
  collector.mReceiver.onReceive(null, null);

  ShadowTrafficStats.setUidRxBytes(11100);
  ShadowTrafficStats.setUidTxBytes(22200);
  assertThat(collector.getTotalBytes(mBytes)).isTrue();

  assertThat(mBytes[RX | MOBILE]).isEqualTo(11000);
  assertThat(mBytes[TX | MOBILE]).isEqualTo(22000);
  assertThat(mBytes[RX | WIFI]).isEqualTo(100);
  assertThat(mBytes[TX | WIFI]).isEqualTo(200);
}