org.robolectric.util.ReflectionHelpers Java Examples
The following examples show how to use
org.robolectric.util.ReflectionHelpers.
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: LocaleChangerShadow.java From adamant-android with GNU General Public License v3.0 | 6 votes |
@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 File: SecureCredentialsManagerTest.java From Auth0.Android with MIT License | 6 votes |
@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 #3
Source File: SecureCredentialsManagerTest.java From Auth0.Android with MIT License | 6 votes |
@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 #4
Source File: SecureCredentialsManagerTest.java From Auth0.Android with MIT License | 6 votes |
@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 #5
Source File: SecureCredentialsManagerTest.java From Auth0.Android with MIT License | 6 votes |
@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 #6
Source File: CryptoUtilTest.java From Auth0.Android with MIT License | 6 votes |
@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 #7
Source File: PromptOptionsUnitTest.java From MaterialTapTargetPrompt with Apache License 2.0 | 6 votes |
@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 #8
Source File: CryptoUtilTest.java From Auth0.Android with MIT License | 6 votes |
@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 #9
Source File: CryptoUtilTest.java From Auth0.Android with MIT License | 6 votes |
@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 #10
Source File: MaterialTapTargetPromptUnitTest.java From MaterialTapTargetPrompt with Apache License 2.0 | 6 votes |
@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 #11
Source File: TestApplication.java From materialistic with Apache License 2.0 | 6 votes |
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 #12
Source File: DesktopIconInfoTest.java From Taskbar with Apache License 2.0 | 6 votes |
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 #13
Source File: UTest.java From Taskbar with Apache License 2.0 | 6 votes |
@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 #14
Source File: PreparedGetCursorTest.java From storio with Apache License 2.0 | 6 votes |
@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 #15
Source File: DefaultStorIOContentResolverTest.java From storio with Apache License 2.0 | 6 votes |
@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 #16
Source File: RequestOldTest.java From Leanplum-Android-SDK with Apache License 2.0 | 6 votes |
/** * 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 #17
Source File: ShadowPreferenceFragmentCompat.java From materialistic with Apache License 2.0 | 5 votes |
@Implementation public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RecyclerView recyclerView = new RecyclerView(container.getContext()); recyclerView.setId(android.R.id.list_container); ReflectionHelpers.setField(realObject, "mList", recyclerView); return recyclerView; }
Example #18
Source File: CryptoUtilTest.java From Auth0.Android with MIT License | 5 votes |
@Test public void shouldThrowOnInvalidAlgorithmParameterExceptionWhenTryingToObtainRSAKeys() 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); doThrow(new InvalidAlgorithmParameterException()).when(keyPairGenerator).initialize(any(AlgorithmParameterSpec.class)); cryptoUtil.getRSAKeyEntry(); }
Example #19
Source File: HokoGradleTestRunner.java From hoko-android with Apache License 2.0 | 5 votes |
private String getType(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "BUILD_TYPE"); } catch (Throwable e) { return null; } }
Example #20
Source File: HokoGradleTestRunner.java From hoko-android with Apache License 2.0 | 5 votes |
private String getFlavor(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "FLAVOR"); } catch (Throwable e) { return null; } }
Example #21
Source File: HokoGradleTestRunner.java From hoko-android with Apache License 2.0 | 5 votes |
private 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; } }
Example #22
Source File: CryptoUtilTest.java From Auth0.Android with MIT License | 5 votes |
@RequiresApi(api = Build.VERSION_CODES.O_MR1) @Test @Config(sdk = 27) public void shouldUseExistingRSAKeyPairOnAPI27AndDown() throws Exception { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 27); KeyStore.PrivateKeyEntry entry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class); PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(true); PowerMockito.when(keyStore.getEntry(KEY_ALIAS, null)).thenReturn(entry); KeyStore.PrivateKeyEntry rsaEntry = cryptoUtil.getRSAKeyEntry(); assertThat(rsaEntry, is(notNullValue())); assertThat(rsaEntry, is(entry)); }
Example #23
Source File: CryptoUtilTest.java From Auth0.Android with MIT License | 5 votes |
@RequiresApi(api = Build.VERSION_CODES.P) @Test @Config(sdk = 28) public void shouldUseExistingRSAKeyPairOnAPI28AndUp() throws Exception { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 28); KeyStore.PrivateKeyEntry entry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class); PowerMockito.when(keyStore.getEntry(KEY_ALIAS, null)).thenReturn(entry); PrivateKey privateKey = null; PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(true); PowerMockito.when(keyStore.getKey(KEY_ALIAS, null)).thenReturn(privateKey); KeyStore.PrivateKeyEntry rsaEntry = cryptoUtil.getRSAKeyEntry(); assertThat(rsaEntry, is(notNullValue())); assertThat(rsaEntry, is(entry)); }
Example #24
Source File: CustomRunner.java From algoliasearch-client-android with MIT License | 5 votes |
private String getType(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "BUILD_TYPE"); } catch (Throwable e) { return null; } }
Example #25
Source File: CustomRunner.java From algoliasearch-client-android with MIT License | 5 votes |
private String getFlavor(Config config) { try { return ReflectionHelpers.getStaticField(config.constants(), "FLAVOR"); } catch (Throwable e) { return null; } }
Example #26
Source File: CustomRunner.java From algoliasearch-client-android with MIT License | 5 votes |
private 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; } }
Example #27
Source File: PromptUtilsUnitTest.java From MaterialTapTargetPrompt with Apache License 2.0 | 5 votes |
@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)); }
Example #28
Source File: ActivityResourceFinderUnitTest.java From MaterialTapTargetPrompt with Apache License 2.0 | 5 votes |
@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 #29
Source File: CorePeripheralTest.java From RxCentralBle with Apache License 2.0 | 5 votes |
@Before public void setup() { MockitoAnnotations.initMocks(this); ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21); corePeripheral = new CorePeripheral(bluetoothDevice, context); }
Example #30
Source File: PopupBridgeTest.java From popup-bridge-android with MIT License | 5 votes |
@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);"); }