@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)); }
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Test @Config(constants = com.auth0.android.auth0.BuildConfig.class, sdk = 21, manifest = Config.NONE) public void shouldNotRequireAuthenticationIfAPI21AndLockScreenDisabled() throws Exception { 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)); }
@RequiresApi(api = Build.VERSION_CODES.M) @Test @Config(constants = com.auth0.android.auth0.BuildConfig.class, sdk = 23, manifest = Config.NONE) public void shouldNotRequireAuthenticationIfAPI23AndLockScreenDisabled() throws Exception { 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)); }
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Test @Config(constants = com.auth0.android.auth0.BuildConfig.class, sdk = 21, manifest = Config.NONE) public void shouldRequireAuthenticationIfAPI21AndLockScreenEnabled() throws Exception { 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)); }
@RequiresApi(api = Build.VERSION_CODES.M) @Test @Config(constants = com.auth0.android.auth0.BuildConfig.class, sdk = 23, manifest = Config.NONE) public void shouldRequireAuthenticationIfAPI23AndLockScreenEnabled() throws Exception { 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)); }
@Test public void shouldThrowOnNoSuchProviderErrorWhenTryingToObtainRSAKeys() throws Exception { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19); exception.expect(KeyException.class); exception.expectMessage("An error occurred while trying to obtain the RSA KeyPair Entry from the Android KeyStore."); 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(); }
@Test public void shouldThrowOnNoSuchAlgorithmErrorWhenTryingToObtainRSAKeys() throws Exception { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19); exception.expect(KeyException.class); exception.expectMessage("An error occurred while trying to obtain the RSA KeyPair Entry from the Android KeyStore."); 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(); }
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(); }
@Before public void setup() { today = Calendar.getInstance(); now = new DayTime(60 * 60 * 10 - 1); // 1 second to 10:00 Context context = RuntimeEnvironment.application; synchronized (ScheduleDatabase.class) { db = Room .inMemoryDatabaseBuilder(context, ScheduleDatabase.class) .allowMainThreadQueries() .build(); ReflectionHelpers.setStaticField(ScheduleDatabase.class, "instance", db); } ScheduleDatabase dd = ScheduleDatabase.get(context); assertThat((Boolean) ReflectionHelpers.getField(dd, "mAllowMainThreadQueries")).isTrue(); // Even app would load it, we load again here to wait for result ScheduleLoader.load(context, db); }
@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!"); } }
@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(); }
@Test @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) public void startActivityTestForPriorJellyBean() { ReflectionHelpers.setStaticField(Build.VERSION.class, SDK_INT, Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1); VersionUtilities.startActivity(activityMock, intentMock, optionsMock); verify(activityMock, times(1)).startActivity(intentMock); verifyNoMoreInteractions(activityMock); }
@Test @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) @Ignore("android.content.res.Resources$NotFoundException: Unable to find resource ID #0x0 in packages") public void setBackgroundTestForPriorJellyBean() { ReflectionHelpers.setStaticField(Build.VERSION.class, SDK_INT, Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1); DeprecationUtilities.setBackground(viewMock, R.drawable.snackbar__design_snackbar_background); verify(viewMock, times(1)).setBackgroundDrawable(any(Drawable.class)); verifyNoMoreInteractions(connectivityManagerMock); }
protected void beforeTest(Sandbox sandbox, Spec spec) throws Throwable { SdkEnvironment sdkEnvironment = (SdkEnvironment) sandbox; RoboSpec roboSpec = (RoboSpec) spec; roboSpec.parallelUniverseInterface = getHooksInterface(sdkEnvironment); Class<TestLifecycle> cl = sdkEnvironment.bootstrappedClass(getTestLifecycleClass()); roboSpec.testLifecycle = ReflectionHelpers.newInstance(cl); final Config config = roboSpec.config; final AndroidManifest appManifest = roboSpec.getAppManifest(); roboSpec.parallelUniverseInterface.setSdkConfig((sdkEnvironment).getSdkConfig()); roboSpec.parallelUniverseInterface.resetStaticState(config); SdkConfig sdkConfig = roboSpec.sdkConfig; Class<?> androidBuildVersionClass = (sdkEnvironment).bootstrappedClass(Build.VERSION.class); ReflectionHelpers.setStaticField(androidBuildVersionClass, "SDK_INT", sdkConfig.getApiLevel()); ReflectionHelpers.setStaticField(androidBuildVersionClass, "RELEASE", sdkConfig.getAndroidVersion()); ReflectionHelpers.setStaticField(androidBuildVersionClass, "CODENAME", sdkConfig.getAndroidCodeName()); PackageResourceTable systemResourceTable = sdkEnvironment.getSystemResourceTable(getJarResolver()); PackageResourceTable appResourceTable = getAppResourceTable(appManifest); // This will always be non empty since every class has basic methods like toString. Method randomMethod = getTestClass().getJavaClass().getMethods()[0]; roboSpec.parallelUniverseInterface.setUpApplicationState( randomMethod, roboSpec.testLifecycle, appManifest, config, new RoutingResourceTable(getCompiletimeSdkResourceTable(), appResourceTable), new RoutingResourceTable(systemResourceTable, appResourceTable), new RoutingResourceTable(systemResourceTable)); roboSpec.testLifecycle.beforeTest(null); }
@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); }
private String getType(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "BUILD_TYPE"); } catch (Throwable e) { return null; } }
private String getFlavor(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "FLAVOR"); } catch (Throwable e) { return null; } }
private String getApplicationId(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "APPLICATION_ID"); } catch (Throwable e) { return null; } }
@SuppressLint("NewApi") @After public void resetWindowManager() throws Exception { // https://github.com/robolectric/robolectric/pull/1741 final Class<?> btclass = Class.forName("com.android.internal.os.BackgroundThread"); Object backgroundThreadSingleton = ReflectionHelpers.getStaticField(btclass,"sInstance"); if (backgroundThreadSingleton!=null) { btclass.getMethod("quit").invoke(backgroundThreadSingleton); ReflectionHelpers.setStaticField(btclass, "sInstance", null); ReflectionHelpers.setStaticField(btclass, "sHandler", null); } // https://github.com/robolectric/robolectric/issues/2068 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. ArraySet<View> dyingViews = ReflectionHelpers.getField(instance, "mDyingViews"); dyingViews.clear(); }
private static String getType(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "BUILD_TYPE"); } catch (Throwable e) { return null; } }
private static String getFlavor(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "FLAVOR"); } catch (Throwable e) { return null; } }
private static String getPackageName(Config config) { try { final String packageName = config.packageName(); if (packageName != null && !packageName.isEmpty()) { return packageName; } else { return ReflectionHelpers.getStaticField(config.constants(), "APPLICATION_ID"); } } catch (Throwable e) { return null; } }
private static String getType(final Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "BUILD_TYPE"); } catch (Throwable e) { return null; } }
private static String getFlavor(final Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "FLAVOR"); } catch (Throwable e) { return null; } }
private static String getPackageName(final Config config) { try { final String packageName = config.packageName(); if (packageName != null && !packageName.isEmpty()) { return packageName; } else { return ReflectionHelpers.getStaticField(config.constants(), "APPLICATION_ID"); } } catch (Throwable e) { return null; } }
@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)); }
@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)); }
@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)); }
@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)); }
@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)); }
@Test public void testIsRtlFirstCharacterNotRtlPreJellyBeanMR1() { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN); final Layout layout = mock(Layout.class); when(layout.isRtlCharAt(0)).thenReturn(false); when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_NORMAL); assertFalse(PromptUtils.isRtlText(layout, null)); }
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1) @Test public void testIsRtlFirstCharacterNotRtlOppositePreJellyBeanMR1() { 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_RTL); final Layout layout = mock(Layout.class); when(layout.isRtlCharAt(0)).thenReturn(false); when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_NORMAL); assertTrue(PromptUtils.isRtlText(layout, resources)); }
@Test public void testIsRtlFirstCharacterNotRtlNotOppositePreJellyBeanMR1() { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN_MR1); final Layout layout = mock(Layout.class); when(layout.isRtlCharAt(0)).thenReturn(false); when(layout.getAlignment()).thenReturn(Layout.Alignment.ALIGN_CENTER); assertFalse(PromptUtils.isRtlText(layout, null)); }
@Deprecated @Test public void testIsVersionBeforeJellyBeanMR1() { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN); assertFalse(PromptUtils.isVersionAfterJellyBeanMR1()); }
@Test public void shouldThrowOnInvalidAlgorithmParameterErrorWhenTryingToObtainRSAKeys() throws Exception { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19); exception.expect(KeyException.class); exception.expectMessage("An error occurred while trying to obtain the RSA KeyPair Entry from the Android KeyStore."); 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); doThrow(new InvalidAlgorithmParameterException()).when(keyPairGenerator).initialize(any(AlgorithmParameterSpec.class)); cryptoUtil.getRSAKeyEntry(); }
@Implementation public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RecyclerView recyclerView = new RecyclerView(container.getContext()); recyclerView.setId(R.id.list); ReflectionHelpers.setField(realObject, "mList", recyclerView); return recyclerView; }
public static BluetoothDevice createMockDevice(@NonNull String address) { final BluetoothDevice device = ReflectionHelpers.newInstance(BluetoothDevice.class); final ShadowBluetoothDeviceExt deviceShadow = BuruberiShadows.shadowOf(device); deviceShadow.setName(randomDeviceName()); deviceShadow.setAddress(address); return device; }
@Implementation public BluetoothGatt connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback) { final BluetoothGatt bluetoothGatt = ReflectionHelpers.newInstance(BluetoothGatt.class); final ShadowBluetoothGatt shadow = BuruberiShadows.shadowOf(bluetoothGatt); shadow.setAutoConnect(autoConnect); shadow.setGattCallback(callback); return bluetoothGatt; }