Java Code Examples for org.robolectric.util.ReflectionHelpers

The following examples show how to use org.robolectric.util.ReflectionHelpers. These examples are extracted from open source projects. 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
@Implementation
public static void initialize(Context context,
                              List<Locale> supportedLocales,
                              MatchingAlgorithm matchingAlgorithm,
                              LocalePreference preference) {
    //Block Multiple Initialization Error
    if (calls.get() == 0) {
        calls.compareAndSet(0, 1);
        Shadow.directlyOn(
                LocaleChanger.class,
                "initialize",
                ReflectionHelpers.ClassParameter.from(Context.class, context),
                ReflectionHelpers.ClassParameter.from(List.class, supportedLocales),
                ReflectionHelpers.ClassParameter.from(MatchingAlgorithm.class, matchingAlgorithm),
                ReflectionHelpers.ClassParameter.from(LocalePreference.class, preference)
        );
    }
}
 
Example 2
Source Project: Leanplum-Android-SDK   Source File: RequestOldTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Runs before every test case.
 */
@Before
public void setUp() throws Exception {
  Application context = RuntimeEnvironment.application;
  assertNotNull(context);

  Leanplum.setApplicationContext(context);

  ReflectionHelpers.setStaticField(LeanplumEventDataManager.class, "instance", null);
  LeanplumEventDataManager.sharedInstance();

  ShadowOperationQueue shadowOperationQueue = new ShadowOperationQueue();

  Field instance = OperationQueue.class.getDeclaredField("instance");
  instance.setAccessible(true);
  instance.set(instance, shadowOperationQueue);

  ShadowLooper.idleMainLooperConstantly(true);
}
 
Example 3
Source Project: Taskbar   Source File: UTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWrapContext() {
    SharedPreferences prefs = U.getSharedPreferences(context);
    prefs.edit().putString(PREF_THEME, "light").apply();
    Context newContext = U.wrapContext(context);
    Integer themeResource = ReflectionHelpers.getField(newContext, "mThemeResource");
    assertNotNull(themeResource);
    assertEquals(R.style.Taskbar, (int) themeResource);
    prefs.edit().putString(PREF_THEME, "dark").apply();
    newContext = U.wrapContext(context);
    themeResource = ReflectionHelpers.getField(newContext, "mThemeResource");
    assertNotNull(themeResource);
    assertEquals(R.style.Taskbar_Dark, (int) themeResource);
    prefs.edit().putString(PREF_THEME, "non-support").apply();
    newContext = U.wrapContext(context);
    assertTrue(newContext instanceof ContextThemeWrapper);
    prefs.edit().remove(PREF_THEME).apply();
    newContext = U.wrapContext(context);
    themeResource = ReflectionHelpers.getField(newContext, "mThemeResource");
    assertNotNull(themeResource);
    assertEquals(R.style.Taskbar, (int) themeResource);
}
 
Example 4
Source Project: Taskbar   Source File: DesktopIconInfoTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testNewDesktopIconInfo(DesktopIconInfo newDesktopIconInfo) {
    assertNotNull(newDesktopIconInfo);
    assertEquals(desktopIconInfo.column, newDesktopIconInfo.column);
    assertEquals(desktopIconInfo.row, newDesktopIconInfo.row);
    assertEquals(
            desktopIconInfo.entry.getComponentName(),
            newDesktopIconInfo.entry.getComponentName()
    );
    assertEquals(
            desktopIconInfo.entry.getPackageName(),
            newDesktopIconInfo.entry.getPackageName()
    );
    assertEquals(
            desktopIconInfo.entry.getLabel(),
            newDesktopIconInfo.entry.getLabel()
    );
    assertNotNull(ReflectionHelpers.getField(desktopIconInfo.entry, "icon"));
    assertNull(ReflectionHelpers.getField(newDesktopIconInfo.entry, "icon"));
}
 
Example 5
@Test
public void targetViewBelowKitKat()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN_MR2);
    final MaterialTapTargetPrompt.Builder builder = createMockBuilder(SCREEN_WIDTH, SCREEN_HEIGHT)
            .setPrimaryText("test");
    final Button button = mock(Button.class);
    when(button.getWindowToken()).then(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation)
        {
            return mock(IBinder.class);
        }
    });
    builder.getResourceFinder().getPromptParentView().addView(button);
    builder.setTarget(button);
    final MaterialTapTargetPrompt prompt = builder.create();
    assertNotNull(prompt);
    prompt.show();
}
 
Example 6
@Test
public void testPromptOptions_IconDrawable_TintList()
{
    final Drawable drawable = mock(Drawable.class);
    final ColorStateList colourStateList = mock(ColorStateList.class);
    final PromptOptions options = UnitTestUtils.createPromptOptions();
    assertEquals(options, options.setIconDrawable(drawable));
    assertEquals(drawable, options.getIconDrawable());
    assertEquals(options, options.setIconDrawableTintList(colourStateList));
    options.setPrimaryText("Primary Text");
    options.setTarget(mock(View.class));
    options.create();
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 16);
    options.create();
    assertEquals(options, options.setIconDrawableTintList(null));
}
 
Example 7
Source Project: Auth0.Android   Source File: SecureCredentialsManagerTest.java    License: MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Test
@Config(sdk = 21)
public void shouldNotRequireAuthenticationIfAPI21AndLockScreenDisabled() {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21);
    Activity activity = spy(Robolectric.buildActivity(Activity.class).create().start().resume().get());

    //Set LockScreen as Disabled
    KeyguardManager kService = mock(KeyguardManager.class);
    when(activity.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    when(kService.isKeyguardSecure()).thenReturn(false);
    when(kService.createConfirmDeviceCredentialIntent("title", "description")).thenReturn(null);

    boolean willAskAuthentication = manager.requireAuthentication(activity, 123, "title", "description");

    assertThat(willAskAuthentication, is(false));
}
 
Example 8
Source Project: Auth0.Android   Source File: SecureCredentialsManagerTest.java    License: MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
@Test
@Config(sdk = 23)
public void shouldNotRequireAuthenticationIfAPI23AndLockScreenDisabled() {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 23);
    Activity activity = spy(Robolectric.buildActivity(Activity.class).create().start().resume().get());

    //Set LockScreen as Disabled
    KeyguardManager kService = mock(KeyguardManager.class);
    when(activity.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    when(kService.isDeviceSecure()).thenReturn(false);
    when(kService.createConfirmDeviceCredentialIntent("title", "description")).thenReturn(null);

    boolean willAskAuthentication = manager.requireAuthentication(activity, 123, "title", "description");

    assertThat(willAskAuthentication, is(false));
}
 
Example 9
Source Project: Auth0.Android   Source File: SecureCredentialsManagerTest.java    License: MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Test
@Config(sdk = 21)
public void shouldRequireAuthenticationIfAPI21AndLockScreenEnabled() {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21);
    Activity activity = spy(Robolectric.buildActivity(Activity.class).create().start().resume().get());

    //Set LockScreen as Enabled
    KeyguardManager kService = mock(KeyguardManager.class);
    when(activity.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    when(kService.isKeyguardSecure()).thenReturn(true);
    when(kService.createConfirmDeviceCredentialIntent("title", "description")).thenReturn(new Intent());

    boolean willAskAuthentication = manager.requireAuthentication(activity, 123, "title", "description");

    assertThat(willAskAuthentication, is(true));
}
 
Example 10
Source Project: Auth0.Android   Source File: SecureCredentialsManagerTest.java    License: MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
@Test
@Config(sdk = 23)
public void shouldRequireAuthenticationIfAPI23AndLockScreenEnabled() {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 23);
    Activity activity = spy(Robolectric.buildActivity(Activity.class).create().start().resume().get());

    //Set LockScreen as Enabled
    KeyguardManager kService = mock(KeyguardManager.class);
    when(activity.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    when(kService.isDeviceSecure()).thenReturn(true);
    when(kService.createConfirmDeviceCredentialIntent("title", "description")).thenReturn(new Intent());

    boolean willAskAuthentication = manager.requireAuthentication(activity, 123, "title", "description");

    assertThat(willAskAuthentication, is(true));
}
 
Example 11
Source Project: Auth0.Android   Source File: CryptoUtilTest.java    License: MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.P)
@Test
@Config(sdk = 28)
public void shouldUseExistingRSAKeyPairRebuildingTheEntryOnAPI28AndUp() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 28);
    KeyStore.PrivateKeyEntry entry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class);
    PrivateKey privateKey = PowerMockito.mock(PrivateKey.class);
    Certificate certificate = PowerMockito.mock(Certificate.class);

    ArgumentCaptor<Object> varargsCaptor = ArgumentCaptor.forClass(Object.class);
    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(true);
    PowerMockito.when(keyStore.getKey(KEY_ALIAS, null)).thenReturn(privateKey);
    PowerMockito.when(keyStore.getCertificate(KEY_ALIAS)).thenReturn(certificate);
    PowerMockito.whenNew(KeyStore.PrivateKeyEntry.class).withAnyArguments().thenReturn(entry);

    KeyStore.PrivateKeyEntry rsaEntry = cryptoUtil.getRSAKeyEntry();
    PowerMockito.verifyNew(KeyStore.PrivateKeyEntry.class).withArguments(varargsCaptor.capture());
    assertThat(rsaEntry, is(notNullValue()));
    assertThat(rsaEntry, is(entry));
    assertThat(varargsCaptor.getAllValues(), is(notNullValue()));
    PrivateKey capturedPrivateKey = (PrivateKey) varargsCaptor.getAllValues().get(0);
    Certificate[] capturedCertificatesArray = (Certificate[]) varargsCaptor.getAllValues().get(1);
    assertThat(capturedPrivateKey, is(privateKey));
    assertThat(capturedCertificatesArray[0], is(certificate));
    assertThat(capturedCertificatesArray.length, is(1));
}
 
Example 12
Source Project: Auth0.Android   Source File: CryptoUtilTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnNoSuchProviderExceptionWhenTryingToObtainRSAKeys() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19);
    exception.expect(IncompatibleDeviceException.class);
    exception.expectMessage("The device is not compatible with the CryptoUtil class");

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    PowerMockito.mockStatic(KeyPairGenerator.class);
    PowerMockito.when(KeyPairGenerator.getInstance(ALGORITHM_RSA, ANDROID_KEY_STORE))
            .thenThrow(new NoSuchProviderException());

    cryptoUtil.getRSAKeyEntry();
}
 
Example 13
Source Project: Auth0.Android   Source File: CryptoUtilTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnNoSuchAlgorithmExceptionWhenTryingToObtainRSAKeys() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19);
    exception.expect(IncompatibleDeviceException.class);
    exception.expectMessage("The device is not compatible with the CryptoUtil class");

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    PowerMockito.mockStatic(KeyPairGenerator.class);
    PowerMockito.when(KeyPairGenerator.getInstance(ALGORITHM_RSA, ANDROID_KEY_STORE))
            .thenThrow(new NoSuchAlgorithmException());

    cryptoUtil.getRSAKeyEntry();
}
 
Example 14
Source Project: materialistic   Source File: TestApplication.java    License: Apache License 2.0 6 votes vote down vote up
private void resetWindowManager() {
    Class clazz = ReflectionHelpers.loadClass(getClass().getClassLoader(), "android.view.WindowManagerGlobal");
    Object instance = ReflectionHelpers.callStaticMethod(clazz, "getInstance");

    // We essentially duplicate what's in {@link WindowManagerGlobal#closeAll} with what's below.
    // The closeAll method has a bit of a bug where it's iterating through the "roots" but
    // bases the number of objects to iterate through by the number of "views." This can result in
    // an {@link java.lang.IndexOutOfBoundsException} being thrown.
    Object lock = ReflectionHelpers.getField(instance, "mLock");

    ArrayList<Object> roots = ReflectionHelpers.getField(instance, "mRoots");
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (lock) {
        for (int i = 0; i < roots.size(); i++) {
            ReflectionHelpers.callInstanceMethod(instance, "removeViewLocked",
                    ReflectionHelpers.ClassParameter.from(int.class, i),
                    ReflectionHelpers.ClassParameter.from(boolean.class, false));
        }
    }

    // Views will still be held by this array. We need to clear it out to ensure
    // everything is released.
    Collection<View> dyingViews = ReflectionHelpers.getField(instance, "mDyingViews");
    dyingViews.clear();

}
 
Example 15
Source Project: storio   Source File: PreparedGetCursorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrowIfNoQueryOrRawQueryIsSet() {
    try {
        final GetCursorStub getStub = GetCursorStub.newInstance();

        final PreparedGetCursor operation = getStub.storIOSQLite
                .get()
                .cursor()
                .withQuery(getStub.query) // will be removed
                .withGetResolver(getStub.getResolverForCursor)
                .prepare();

        ReflectionHelpers.setField(operation, "query", null);
        ReflectionHelpers.setField(operation, "rawQuery", null);
        operation.getData();

        failBecauseExceptionWasNotThrown(IllegalStateException.class);
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Either rawQuery or query should be set!");
    }
}
 
Example 16
Source Project: storio   Source File: DefaultStorIOContentResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUseCustomHandlerForContentObservers() {
    ContentResolver contentResolver = mock(ContentResolver.class);
    ArgumentCaptor<ContentObserver> observerArgumentCaptor = ArgumentCaptor.forClass(ContentObserver.class);
    doNothing().when(contentResolver)
            .registerContentObserver(any(Uri.class), anyBoolean(), observerArgumentCaptor.capture());
    Handler handler = mock(Handler.class);

    StorIOContentResolver storIOContentResolver = DefaultStorIOContentResolver.builder()
            .contentResolver(contentResolver)
            .contentObserverHandler(handler)
            .defaultRxScheduler(null)
            .build();

    Disposable disposable = storIOContentResolver.observeChangesOfUri(mock(Uri.class), LATEST).subscribe();

    assertThat(observerArgumentCaptor.getAllValues()).hasSize(1);
    ContentObserver contentObserver = observerArgumentCaptor.getValue();
    Object actualHandler = ReflectionHelpers.getField(contentObserver, "mHandler");
    assertThat(actualHandler).isEqualTo(handler);

    disposable.dispose();
}
 
Example 17
Source Project: RxCentralBle   Source File: CorePeripheralTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  MockitoAnnotations.initMocks(this);

  ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21);

  corePeripheral = new CorePeripheral(bluetoothDevice, context);
}
 
Example 18
Source Project: popup-bridge-android   Source File: PopupBridgeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void onBrowserSwitchResult_whenResultIsError_reportsError() {
    BrowserSwitchResult result = BrowserSwitchResult.ERROR;
    ReflectionHelpers.callInstanceMethod(result, "setErrorMessage",
            new ReflectionHelpers.ClassParameter<>(String.class, "Browser switch error"));

    mPopupBridge.onBrowserSwitchResult(1, result, null);

    assertEquals("new Error('Browser switch error')", mWebView.mError);
    assertEquals(mWebView.mJavascriptEval, "window.popupBridge.onComplete(new Error('Browser switch error'), null);");
}
 
Example 19
Source Project: Taskbar   Source File: TaskbarControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Config(shadows = {TaskbarShadowScrollView.class})
public void testScrollTaskbarForScrollViewLocation() {
    // We only provide enhanced ShadowScrollView with scrollTo supported, so we should
    // choose the layout uses the ScrollView instead of HorizontalScrollView.
    String taskbarPosition = POSITION_BOTTOM_VERTICAL_LEFT;
    int layoutId = uiController.getTaskbarLayoutId(taskbarPosition);
    LinearLayout layout = (LinearLayout) LayoutInflater.from(context).inflate(layoutId, null);
    FrameLayout scrollView = layout.findViewById(R.id.taskbar_scrollview);
    LinearLayout taskbar = layout.findViewById(R.id.taskbar);
    int taskbarWidth = 200;
    int taskbarHeight = 50;
    // Change LayoutParams doesn't work with robolectric, so we should use reflection
    // to change the location directly.
    ReflectionHelpers.setField(taskbar, "mLeft", 0);
    ReflectionHelpers.setField(taskbar, "mTop", 0);
    ReflectionHelpers.setField(taskbar, "mRight", taskbarWidth);
    ReflectionHelpers.setField(taskbar, "mBottom", taskbarHeight);

    BooleanAnswer isVerticalAnswer = new BooleanAnswer();
    PowerMockito.spy(TaskbarPosition.class);
    when(TaskbarPosition.isVertical(taskbarPosition)).thenAnswer(isVerticalAnswer);

    isVerticalAnswer.answer = false;
    uiController.scrollTaskbar(scrollView, taskbar, taskbarPosition, "false", true);
    assertEquals(0, scrollView.getScrollX());
    assertEquals(0, scrollView.getScrollY());
    uiController.scrollTaskbar(scrollView, taskbar, taskbarPosition, "true", true);
    assertEquals(taskbarWidth, scrollView.getScrollX());
    assertEquals(taskbarHeight, scrollView.getScrollY());

    isVerticalAnswer.answer = true;
    uiController.scrollTaskbar(scrollView, taskbar, taskbarPosition, "true", true);
    assertEquals(0, scrollView.getScrollX());
    assertEquals(0, scrollView.getScrollY());
    uiController.scrollTaskbar(scrollView, taskbar, taskbarPosition, "false", true);
    assertEquals(taskbarWidth, scrollView.getScrollX());
    assertEquals(taskbarHeight, scrollView.getScrollY());
}
 
Example 20
Source Project: Taskbar   Source File: TaskbarControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
private LauncherActivityInfo generateTestLauncherActivityInfo(Context context,
                                                              ActivityInfo activityInfo,
                                                              int userHandleId) {
    return
            ReflectionHelpers.callConstructor(
                    LauncherActivityInfo.class,
                    from(Context.class, context),
                    from(ActivityInfo.class, activityInfo),
                    from(UserHandle.class, UserHandle.getUserHandleForUid(userHandleId))
            );
}
 
Example 21
Source Project: Taskbar   Source File: UTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testShowErrorDialog() {
    RunnableHooker onFinish = new RunnableHooker();
    String appOpCommand = "app-op-command";
    AlertDialog dialog =
            ReflectionHelpers.callStaticMethod(
                    U.class,
                    "showErrorDialog",
                    from(Context.class, context),
                    from(String.class, appOpCommand),
                    from(Callbacks.class, new Callbacks(null, onFinish))
            );
    ShadowAlertDialog shadowDialog = Shadows.shadowOf(dialog);
    Resources resources = context.getResources();
    assertEquals(
            resources.getString(R.string.tb_error_dialog_title),
            shadowDialog.getTitle()
    );
    assertEquals(
            resources.getString(
                    R.string.tb_error_dialog_message,
                    context.getPackageName(),
                    appOpCommand
            ),
            shadowDialog.getMessage()
    );
    Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
    assertEquals(resources.getString(R.string.tb_action_ok), button.getText());
    assertFalse(shadowDialog.isCancelable());
    button.performClick();
    assertTrue(onFinish.hasRun());
}
 
Example 22
Source Project: Taskbar   Source File: UTest.java    License: Apache License 2.0 5 votes vote down vote up
private int getActivityOptionsStackId(ActivityOptions options) {
    String methodName;
    if (U.getCurrentApiVersion() >= 28.0f) {
        methodName = "getLaunchWindowingMode";
    } else {
        methodName = "getLaunchStackId";
    }
    return ReflectionHelpers.callInstanceMethod(options, methodName);
}
 
Example 23
@Test
public void testGetDrawablePreLollipop()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 20);
    final Drawable resource = mock(Drawable.class);
    final int resourceId = 64532;
    final DialogFragment dialogFragment = spy(new DialogFragment());
    final SupportFragmentResourceFinder resourceFinder = new SupportFragmentResourceFinder(dialogFragment);
    final Resources resources = mock(Resources.class);
    final Context context = mock(Context.class);
    when(dialogFragment.getContext()).thenReturn(context);
    when(dialogFragment.getResources()).thenReturn(resources);
    when(resources.getDrawable(resourceId)).thenReturn(resource);
    assertEquals(resource, resourceFinder.getDrawable(resourceId));
}
 
Example 24
@Test
public void targetViewBelowKitKatNotAttached()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN_MR2);
    final MaterialTapTargetPrompt.Builder builder = createMockBuilder(SCREEN_WIDTH, SCREEN_HEIGHT)
            .setPrimaryText("test");
    final Button button = mock(Button.class);
    builder.setTarget(button);
    final MaterialTapTargetPrompt prompt = builder.show();
    assertNotNull(prompt);
}
 
Example 25
@Test
public void testGetDrawablePreLollipop()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 20);
    final Drawable resource = mock(Drawable.class);
    final int resourceId = 64532;
    final Activity activity = mock(Activity.class);
    final ActivityResourceFinder resourceFinder = new ActivityResourceFinder(activity);
    final Resources resources = mock(Resources.class);
    when(activity.getResources()).thenReturn(resources);
    when(resources.getDrawable(resourceId)).thenReturn(resource);
    assertEquals(resource, resourceFinder.getDrawable(resourceId));
}
 
Example 26
@Test
public void testImmersiveModeCompatPromptBackground_getDisplayMetrics_JELLY_BEAN()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN);
    final Rect clipBounds = new Rect(0, 0, 480, 800);
    final RectF focalBounds = new RectF(300, 100, 100, 700);
    final PromptOptions options = createOptions(clipBounds, focalBounds);
    final ImmersiveModeCompatPromptBackground promptBackground =
            (ImmersiveModeCompatPromptBackground) options.getPromptBackground();
    assertNotNull(promptBackground.getDisplayMetrics());
    assertEquals(480, promptBackground.getDisplayMetrics().widthPixels);
    assertEquals(800, promptBackground.getDisplayMetrics().heightPixels);
}
 
Example 27
@Test
public void testIsRtlPreIceCreamSandwich()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.HONEYCOMB_MR2);
    final Layout layout = mock(Layout.class);
    when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_NORMAL);
    assertFalse(PromptUtils.isRtlText(layout, null));
}
 
Example 28
@Test
public void testIsRtlPreIceCreamSandwichOpposite()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.HONEYCOMB_MR2);
    final Layout layout = mock(Layout.class);
    when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_OPPOSITE);
    assertTrue(PromptUtils.isRtlText(layout, null));
}
 
Example 29
@Test
public void testIsRtlPreIceCreamSandwichCentre()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.HONEYCOMB_MR2);
    final Layout layout = mock(Layout.class);
    when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_CENTER);
    assertFalse(PromptUtils.isRtlText(layout, null));
}
 
Example 30
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Test
public void testIsRtlFirstCharacterNotRtl()
{
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN_MR1);
    final Resources resources = mock(Resources.class);
    final Configuration configuration = mock(Configuration.class);
    when(resources.getConfiguration()).thenReturn(configuration);
    when(configuration.getLayoutDirection()).thenReturn(View.LAYOUT_DIRECTION_LTR);
    final Layout layout = mock(Layout.class);
    when(layout.isRtlCharAt(0)).thenReturn(false);
    when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_NORMAL);
    assertFalse(PromptUtils.isRtlText(layout, resources));
}