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

项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that rejections propagate. */
@Test
public void rejectionChaining() {
    final Value value = new Value();
    Promise<Integer> promise = new Promise<Integer>();

    Promise<Integer> result =
            promise.then(this.<Integer>identity()).then(this.<Integer>identity());

    result.then(this.<Integer>pass(), this.<Exception>setValue(value, 5));

    promise.reject(new Exception());
    ShadowHandler.runMainLooperToEndOfTasks();

    assertEquals(value.get(), 5);
    assertTrue(result.isRejected());
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that Promises get rejected if a Function throws. */
@Test
public void rejectOnThrow() {
    Value value = new Value();
    Promise<Integer> promise = new Promise<Integer>();
    promise.then(new Promise.Function<Integer, Integer>() {
        @Override
        public Integer apply(Integer argument) {
            throw new IllegalArgumentException();
        }
    }).then(this.<Integer>pass(), this.<Exception>setValue(value, 5));

    promise.fulfill(0);

    ShadowHandler.runMainLooperToEndOfTasks();
    assertEquals(value.get(), 5);
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that Promises get rejected if an AsyncFunction throws. */
@Test
public void rejectOnAsyncThrow() {
    Value value = new Value();
    Promise<Integer> promise = new Promise<Integer>();

    promise.then(new Promise.AsyncFunction<Integer, Integer>() {
        @Override
        public Promise<Integer> apply(Integer argument) {
            throw new IllegalArgumentException();
        }
    }).then(this.<Integer>pass(), this.<Exception>setValue(value, 5));

    promise.fulfill(0);

    ShadowHandler.runMainLooperToEndOfTasks();
    assertEquals(value.get(), 5);
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that Promises get rejected if an AsyncFunction rejects. */
@Test
public void rejectOnAsyncReject() {
    Value value = new Value();
    Promise<Integer> promise = new Promise<Integer>();
    final Promise<Integer> inner = new Promise<Integer>();

    promise.then(new Promise.AsyncFunction<Integer, Integer>() {
        @Override
        public Promise<Integer> apply(Integer argument) {
            return inner;
        }
    }).then(this.<Integer>pass(), this.<Exception>setValue(value, 5));

    promise.fulfill(0);

    ShadowHandler.runMainLooperToEndOfTasks();
    assertEquals(value.get(), 0);

    inner.reject();

    ShadowHandler.runMainLooperToEndOfTasks();
    assertEquals(value.get(), 5);
}
项目:talkback    文件:AutoScanControllerTest.java   
@Test
public void testAutoReverseReverse_switchesDirectionAndSelects() {
    mAutoScanControllerForOptionScanning.autoScanActivated(false);
    ShadowHandler.runMainLooperOneTask();
    verify(mOptionManager, times(2)).selectOption(1);

    mAutoScanControllerForOptionScanning.autoScanActivated(true);
    ShadowHandler.runMainLooperOneTask();
    verify(mOptionManager, times(2)).selectOption(1);

    mAutoScanControllerForOptionScanning.autoScanActivated(true);
    verify(mOptionManager, times(2)).selectOption(1);
    verify(mOptionManager, times(1)).moveToParent(true);
    verify(mOptionManager, times(1))
            .addOptionManagerListener((OptionManager.OptionManagerListener) anyObject());
}
项目:talkback    文件:AutoScanControllerTest.java   
@Test
public void testReverseAutoAuto_switchesDirectionAndSelects() {
    mAutoScanControllerForOptionScanning.autoScanActivated(true);
    ShadowHandler.runMainLooperOneTask();
    verify(mOptionManager, times(2)).moveToParent(true);

    mAutoScanControllerForOptionScanning.autoScanActivated(false);
    ShadowHandler.runMainLooperOneTask();
    verify(mOptionManager, times(2)).moveToParent(true);

    mAutoScanControllerForOptionScanning.autoScanActivated(false);
    verify(mOptionManager, times(2)).moveToParent(true);
    verify(mOptionManager, times(1)).selectOption(1);
    verify(mOptionManager, times(1))
            .addOptionManagerListener((OptionManager.OptionManagerListener) anyObject());
}
项目:chailmis-android    文件:DispenseActivityTest.java   
@Test
public void testThatIfAllDispensingItemsHaveQuantitiesNoToastIsMade() throws Exception {

    DispenseActivity dispenseActivity = getDispenseActivity();

    GridView mockGridView = mock(GridView.class);
    SelectedCommoditiesAdapter mockCommoditiesAdapter = mock(SelectedCommoditiesAdapter.class);
    View mockListItemView = mock(View.class);
    EditText mockEditText = new EditText(application);
    mockEditText.setText("12");

    when(mockListItemView.findViewById(R.id.editTextQuantity)).thenReturn(mockEditText);
    when(mockGridView.getChildAt(anyInt())).thenReturn(mockListItemView);
    when(mockGridView.getChildCount()).thenReturn(1);
    when(mockCommoditiesAdapter.getItem(anyInt())).thenReturn(new BaseCommodityViewModel(new Commodity("food")));
    when(mockGridView.getAdapter()).thenReturn(mockCommoditiesAdapter);

    dispenseActivity.gridViewSelectedCommodities = mockGridView;
    dispenseActivity.findViewById(R.id.buttonSubmitDispense).performClick();
    ShadowHandler.idleMainLooper();

    assertThat(ShadowToast.getTextOfLatestToast(), is(Matchers.nullValue()));


}
项目:chailmis-android    文件:DispenseActivityTest.java   
@Test
public void testThatIfAnyOfTheDispensingItemsHaveErrorsAToastIsMade() throws Exception {
    DispenseActivity dispenseActivity = getDispenseActivity();

    GridView mockGridView = mock(GridView.class);
    View mockListItemView = mock(View.class);
    EditText mockEditText = new EditText(application);

    mockEditText.setText("12");
    mockEditText.setError("error");
    SelectedCommoditiesAdapter mockSelectedCommoditiesAdapter = mock(SelectedCommoditiesAdapter.class);

    when(mockListItemView.findViewById(R.id.editTextQuantity)).thenReturn(mockEditText);
    when(mockSelectedCommoditiesAdapter.getItem(anyInt())).thenReturn(new BaseCommodityViewModel(new Commodity("food")));
    when(mockSelectedCommoditiesAdapter.getCount()).thenReturn(1);
    when(mockSelectedCommoditiesAdapter.getView(anyInt(), org.mockito.Matchers.any(View.class), org.mockito.Matchers.any(ViewGroup.class))).thenReturn(mockListItemView);
    when(mockGridView.getAdapter()).thenReturn(mockSelectedCommoditiesAdapter);
    when(mockGridView.getChildAt(anyInt())).thenReturn(mockListItemView);
    when(mockGridView.getChildCount()).thenReturn(1);

    dispenseActivity.gridViewSelectedCommodities = mockGridView;
    dispenseActivity.findViewById(R.id.buttonSubmitDispense).performClick();
    ShadowHandler.idleMainLooper();

    assertThat(ShadowToast.getTextOfLatestToast(), equalTo(application.getString(R.string.dispense_submit_validation_message_errors)));
}
项目:chailmis-android    文件:DispenseActivityTest.java   
@Test
public void testThatIfAllDispensingItemsHaveNoQuantitiesAToastIsMade() throws Exception {
    DispenseActivity dispenseActivity = getDispenseActivity();

    GridView mockGridView = mock(GridView.class);
    View mockListItemView = mock(View.class);
    EditText mockEditText = new EditText(application);
    SelectedCommoditiesAdapter mockSelectedCommoditiesAdapter = mock(SelectedCommoditiesAdapter.class);

    when(mockListItemView.findViewById(R.id.editTextQuantity)).thenReturn(mockEditText);
    when(mockGridView.getAdapter()).thenReturn(mockSelectedCommoditiesAdapter);
    when(mockSelectedCommoditiesAdapter.getItem(anyInt())).thenReturn(new BaseCommodityViewModel(new Commodity("food")));
    when(mockSelectedCommoditiesAdapter.getCount()).thenReturn(1);
    when(mockSelectedCommoditiesAdapter.getView(anyInt(), org.mockito.Matchers.any(View.class), org.mockito.Matchers.any(ViewGroup.class))).thenReturn(mockListItemView);
    when(mockGridView.getChildAt(anyInt())).thenReturn(mockListItemView);
    when(mockGridView.getChildCount()).thenReturn(1);

    dispenseActivity.gridViewSelectedCommodities = mockGridView;
    dispenseActivity.findViewById(R.id.buttonSubmitDispense).performClick();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), equalTo(application.getString(R.string.dispense_submit_validation_message_filled)));
}
项目:chailmis-android    文件:DispenseActivityTest.java   
@Test
public void testThatIfAllDispensingItemsHaveZeroQuantitiesAToastIsMade() throws Exception {
    DispenseActivity dispenseActivity = getDispenseActivity();

    GridView mockGridView = mock(GridView.class);
    View mockListItemView = mock(View.class);
    SelectedCommoditiesAdapter mockSelectedCommoditiesAdapter = mock(SelectedCommoditiesAdapter.class);
    EditText mockEditText = new EditText(application);

    mockEditText.setText("0");

    when(mockListItemView.findViewById(R.id.editTextQuantity)).thenReturn(mockEditText);
    when(mockListItemView.findViewById(R.id.editTextQuantity)).thenReturn(mockEditText);
    when(mockGridView.getAdapter()).thenReturn(mockSelectedCommoditiesAdapter);
    when(mockSelectedCommoditiesAdapter.getItem(anyInt())).thenReturn(new BaseCommodityViewModel(new Commodity("food")));
    when(mockSelectedCommoditiesAdapter.getCount()).thenReturn(1);
    when(mockSelectedCommoditiesAdapter.getView(anyInt(), org.mockito.Matchers.any(View.class), org.mockito.Matchers.any(ViewGroup.class))).thenReturn(mockListItemView);
    when(mockGridView.getChildAt(anyInt())).thenReturn(mockListItemView);
    when(mockGridView.getChildCount()).thenReturn(1);

    dispenseActivity.gridViewSelectedCommodities = mockGridView;
    dispenseActivity.findViewById(R.id.buttonSubmitDispense).performClick();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), equalTo(application.getString(R.string.dispense_submit_validation_message_zero)));
}
项目:chailmis-android    文件:AdjustmentsActivityTest.java   
@Ignore("WIP-JOB")
public void shouldShowErrorToastIfNotAVaccine() throws Exception {
    ArrayList<AdjustmentsViewModel> commodities = new ArrayList<>();

    Commodity commodity = mock(Commodity.class);
    when(commodity.isVaccine()).thenReturn(false);
    when(commodity.getName()).thenReturn("Panadol");

    AdjustmentsViewModel adjustmentsViewModel = new AdjustmentsViewModel(commodity, 12, false);
    adjustmentsViewModel.setAdjustmentReason(AdjustmentReason.RETURNED_TO_LGA);
    commodities.add(adjustmentsViewModel);

    AdjustmentsActivity activity = getAdjustmentsActivity();
    EventBus.getDefault().post(new CommodityToggledEvent(adjustmentsViewModel));
    activity.spinnerAdjustmentReason.setSelection(4);

    Button submitButton = activity.getSubmitButton();
    submitButton.performClick();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), is(application.getResources().getString(R.string.not_related_to_vaccine)));
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that promises can chain asynchronous functions correctly. */
@Test
public void promiseChainingAsyncFunctions() {
    Promise<Integer> promise = new Promise<Integer>();
    final Value value = new Value();

    final Promise<String> innerPromise = new Promise<String>();

    promise.then(new Promise.AsyncFunction<Integer, String>() {
                @Override
                public Promise<String> apply(Integer arg) {
                    return innerPromise;
                }
            }).then(new Callback<String>(){
                @Override
                public void onResult(String result) {
                    value.set(result.length());
                }
            });

    assertEquals(0, value.get());

    promise.fulfill(5);
    ShadowHandler.runMainLooperToEndOfTasks();
    assertEquals(0, value.get());

    innerPromise.fulfill("abc");
    ShadowHandler.runMainLooperToEndOfTasks();
    assertEquals(3, value.get());
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that a Promise that does not use its result does not throw on rejection. */
@Test
public void rejectPromiseNoCallbacks() {
    Promise<Integer> promise = new Promise<Integer>();

    boolean caught = false;
    try {
        promise.reject();
        ShadowHandler.runMainLooperToEndOfTasks();
    } catch (UnhandledRejectionException e) {
        caught = true;
    }
    assertFalse(caught);
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that a Promise that uses its result throws on rejection if it has no handler. */
@Test
public void rejectPromiseNoHandler() {
    Promise<Integer> promise = new Promise<Integer>();
    promise.then(this.<Integer>identity()).then(this.<Integer>pass());

    boolean caught = false;
    try {
        promise.reject();
        ShadowHandler.runMainLooperToEndOfTasks();
    } catch (UnhandledRejectionException e) {
        caught = true;
    }
    assertTrue(caught);
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that a Promise that handles rejection does not throw on rejection. */
@Test
public void rejectPromiseHandled() {
    Promise<Integer> promise = new Promise<Integer>();
    promise.then(this.<Integer>identity()).then(this.<Integer>pass(), this.<Exception>pass());

    boolean caught = false;
    try {
        promise.reject();
        ShadowHandler.runMainLooperToEndOfTasks();
    } catch (UnhandledRejectionException e) {
        caught = true;
    }
    assertFalse(caught);
}
项目:chromium-net-for-android    文件:PromiseTest.java   
/** Tests that rejections carry the exception information. */
@Test
public void rejectionInformation() {
    Promise<Integer> promise = new Promise<Integer>();
    promise.then(this.<Integer>pass());

    String message = "Promise Test";
    try {
        promise.reject(new NegativeArraySizeException(message));
        ShadowHandler.runMainLooperToEndOfTasks();
    } catch (UnhandledRejectionException e) {
        assertTrue(e.getCause() instanceof NegativeArraySizeException);
        assertEquals(e.getCause().getMessage(), message);
    }
}
项目:talkback    文件:OptionManagerTest.java   
@Test
public void testOptionScanningEnabled_highlightsMenuButton() {
    mSharedPreferences.edit()
            .putString(mContext.getString(R.string.pref_scanning_methods_key),
                    mContext.getString(R.string.option_scanning_key))
            .commit();
    mOptionManager.onSharedPreferenceChanged(mSharedPreferences, null);
    when(mOverlayController.getMenuButtonLocation()).thenReturn(MENU_BUTTON_BOUNDS);

    /* add a context menu with two items to the tree */
    CharSequence globalActionLabel0 = "global action label 0";
    CharSequence globalActionLabel1 = "global action label 1";
    GlobalActionNode globalNode0 = new GlobalActionNode(0, null, globalActionLabel0);
    GlobalActionNode globalNode1 = new GlobalActionNode(1, null, globalActionLabel1);
    ContextMenuNode contextMenu = new ContextMenuNode(globalNode0, globalNode1);
    mSelectionNode = new OptionScanSelectionNode(mSelectionNode, contextMenu);

    mOptionManager.clearFocusIfNewTree(mSelectionNode);
    mOptionManager.selectOption(0);
    verify(mOverlayController, times(1)).drawMenuButton();

    ShadowHandler.runMainLooperToEndOfTasks();

    verify(mOverlayController, times(2)).highlightPerimeterOfRects(
            mHighlightCaptor.capture(), mPaintCaptor.capture());

    List<Collection<Rect>> capturedHighlights = mHighlightCaptor.getAllValues();
    assertTrue(capturedHighlights.get(0).contains(NODE_BOUNDS_1));
    assertTrue(capturedHighlights.get(0).contains(NODE_BOUNDS_2));
    assertTrue(capturedHighlights.get(1).contains(MENU_BUTTON_BOUNDS));
}
项目:talkback    文件:ContextMenuNodeTest.java   
@Test
public void testShowSelections_highlightsButtons() {
    LinearLayout addedLayout = getLinearLayoutAddedWithShowSelections();

    /* Set up bounds since nothing is actually doing a layout here. */
    setBoundsForView(addedLayout.getChildAt(0), BOUNDS_1);
    setBoundsForView(addedLayout.getChildAt(1), BOUNDS_2);
    setBoundsForView(addedLayout.getChildAt(2), BOUNDS_3);

    /* Allow handler to run */
    ShadowHandler.runMainLooperToEndOfTasks();

    /* Verify first highlight */
    verify(mMockOverlayController).highlightPerimeterOfRects(
            mRectSetCaptor.capture(), eq(mPaints[0]));
    Iterator<Rect> rectIterator1 = mRectSetCaptor.getValue().iterator();
    assertEquals(BOUNDS_1, rectIterator1.next());
    assertFalse(rectIterator1.hasNext());
    /* Verify second highlight */
    verify(mMockOverlayController).highlightPerimeterOfRects(
            mRectSetCaptor.capture(), eq(mPaints[1]));
    Iterator<Rect> rectIterator2 = mRectSetCaptor.getValue().iterator();
    Rect rect1 = rectIterator2.next();
    Rect rect2 = rectIterator2.next();
    assertFalse(rectIterator2.hasNext());
    assertTrue((rect1.equals(BOUNDS_2)) || (rect2.equals(BOUNDS_2)));
    assertTrue((rect1.equals(BOUNDS_3)) || (rect2.equals(BOUNDS_3)));
    /* Verify that Clear Focus was not added in the context menu */
    verify(mMockOverlayController).highlightPerimeterOfRects(
            mRectSetCaptor.capture(), eq(mPaints[2]));
    Iterator<Rect> rectIterator3 = mRectSetCaptor.getValue().iterator();
    assertFalse(rectIterator3.hasNext());
}
项目:talkback    文件:AutoScanControllerTest.java   
@Test
public void onClearFocus_stopsScanning() {
    mAutoScanControllerForOptionScanning.autoScanActivated(false);
    mAutoScanControllerForOptionScanning.onOptionManagerClearedFocus();
    ShadowHandler.runMainLooperOneTask();
    verify(mOptionManager, times(1)).selectOption(1);
    verify(mOptionManager, times(1))
            .addOptionManagerListener((OptionManager.OptionManagerListener) anyObject());
    verifyNoMoreInteractions(mOptionManager);
}
项目:Android_Yellow_Pages_App_TDD    文件:MainActivityTest.java   
@Test
public void onSearchButtonClicked_shouldDisplayToastIfEditTextsAreEmpty() {
    Button searchButton = (Button) mMainActivity.findViewById(R.id.search_button);
    searchButton.performClick();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast()).isEqualTo("Please fill in both fields!");
}
项目:chailmis-android    文件:OrderActivityTest.java   
@Test    
public void shouldShowMessageAboutOutstandingAlertsIfAny() throws Exception {
    Intent intent = new Intent();
    when(alertsService.getNumberOfRoutineOrderAlerts()).thenReturn(2);
    intent.putExtra(AlertClickListener.ORDER_TYPE, OrderType.ROUTINE);
    orderActivity = Robolectric.buildActivity(OrderActivity.class).withIntent(intent).create().start().resume().visible().get();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), is(application.getString(R.string.outstanding_routine_order_alerts_message)));
}
项目:chailmis-android    文件:OrderActivityTest.java   
@Test    
public void shouldNotShowMessageAboutOutstandingAlertsIfItIsOnlyOne() throws Exception {
    Intent intent = new Intent();
    when(alertsService.getNumberOfRoutineOrderAlerts()).thenReturn(1);
    intent.putExtra(AlertClickListener.ORDER_TYPE, OrderType.ROUTINE);
    orderActivity = Robolectric.buildActivity(OrderActivity.class).withIntent(intent).create().start().resume().visible().get();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), is(nullValue()));
}
项目:chailmis-android    文件:RegisterActivityTest.java   
@Test
public void testMessageShouldBeShownIfRegistrationIsSuccessful() {
    performSuccessfulRegistration();

    ShadowHandler.idleMainLooper();
    assertThat(getTextOfLatestToast(), equalTo(registerActivity.getString(R.string.registration_successful_message)));
}
项目:chailmis-android    文件:RegisterActivityTest.java   
@Test
public void testErrorShouldBeShownIfRegistrationFailed() {
    String errorMessage = "Some failure message";
    when(mockUserService.register(anyString(), anyString())).thenThrow(new LmisException(errorMessage));
    fillTextField(id.textUsername, "adminsdsd");
    fillTextField(id.textPassword, "districtsds");
    getRegisterButton().performClick();

    ShadowHandler.idleMainLooper();
    assertThat(getTextOfLatestToast(), equalTo(errorMessage));

}
项目:chailmis-android    文件:ReceiveActivityTest.java   
@Test
public void shouldNotLetUserSubmitFormWhenAllocationIdHasError() throws Exception {
    ReceiveActivity receiveActivity = getReceiveActivity();
    setSource(receiveActivity, application.getString(R.string.lga_for_receive));
    receiveActivity.textViewAllocationId.setText("aoiiouads");
    receiveActivity.buttonSubmitReceive.performClick();

    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), equalTo(application.getString(R.string.receive_submit_validation_message_allocation_id)));
}
项目:chailmis-android    文件:ReceiveActivityTest.java   
@Test
public void shouldNotRequireAllocationIdWhenNotRecievingFromLGA() throws Exception {
    ReceiveActivity receiveActivity = getReceiveActivity();
    setSource(receiveActivity, application.getString(R.string.zonal_store_for_receive));
    ANDROID.assertThat(receiveActivity.textViewAllocationId).isDisabled();
    setupValidCommodity(receiveActivity);
    receiveActivity.getSubmitButton().performClick();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), is(nullValue()));
}
项目:FullRobolectricTestSample    文件:Robolectric.java   
public static ShadowHandler shadowOf(Handler instance) {
  return (ShadowHandler) shadowOf_(instance);
}
项目:chailmis-android    文件:ReceiveActivityTest.java   
@Test
public void shouldLetUserSubmitFormWhenAllocationIdAndQuantitiesAreValid() throws Exception {
    performSubmitWithValidFields();
    ShadowHandler.idleMainLooper();
    assertThat(ShadowToast.getTextOfLatestToast(), is(nullValue()));
}