Java Code Examples for org.robolectric.RuntimeEnvironment#application()

The following examples show how to use org.robolectric.RuntimeEnvironment#application() . 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: RecentlyUsedListsNullHandlingTest.java    From opentasks with Apache License 2.0 6 votes vote down vote up
/**
 * Test that even if "null" string had been stored incorrectly previously, it doesn't affect the usage.
 */
@Test
public void test_getRecentFromList_that_the_stored_null_string_is_ignored()
{
    Application context = RuntimeEnvironment.application;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    prefs.edit().putString(PREFERENCE_KEY, "null,1,2").apply();
    List<Long> allowedList = new ArrayList<>();
    allowedList.add(2L);
    assertThat(RecentlyUsedLists.getRecentFromList(context, allowedList), is(2L));

    prefs.edit().putString(PREFERENCE_KEY, "1,null,2").apply();
    allowedList = new ArrayList<>();
    allowedList.add(5L);
    assertThat(RecentlyUsedLists.getRecentFromList(context, allowedList), is(5L));

    prefs.edit().putString(PREFERENCE_KEY, "1,2,null").apply();
    allowedList = new ArrayList<>();
    allowedList.add(2L);
    assertThat(RecentlyUsedLists.getRecentFromList(context, allowedList), is(2L));
}
 
Example 2
Source File: RequestOldTest.java    From Leanplum-Android-SDK with 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 File: SnackbarBuilderTest.java    From SnackbarBuilder with Apache License 2.0 6 votes vote down vote up
@Test
public void givenActionTextAndClickListener_whenBuildWrapper_thenActionTextAndClickListenerSet() {
  RuntimeEnvironment.application.setTheme(R.style.TestSnackbarBuilder_AppTheme);
  CoordinatorLayout parent = new CoordinatorLayout(RuntimeEnvironment.application);

  SnackbarWrapper wrapper = new SnackbarBuilder(parent)
      .actionText("action")
      .actionClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
          view.setBackgroundColor(Color.RED);
        }
      })
      .buildWrapper();

  assertThat(wrapper.getActionText()).isEqualTo("action");
  View actionView = wrapper.getView().findViewById(R.id.snackbar_action);
  actionView.performClick();
  Assertions.assertThat((ColorDrawable) actionView.getBackground()).hasColor(Color.RED);
}
 
Example 4
Source File: SnackbarBuilderTest.java    From SnackbarBuilder with Apache License 2.0 6 votes vote down vote up
@Test
public void givenIcon_whenBuild_thenIconAddedToSnackbar() {
  RuntimeEnvironment.application.setTheme(R.style.TestSnackbarBuilder_AppTheme);
  CoordinatorLayout parent = new CoordinatorLayout(RuntimeEnvironment.application);

  Snackbar snackbar = new SnackbarBuilder(parent)
      .message("messsage")
      .icon(drawable)
      .iconMargin(10)
      .build();

  TextView messageView = (TextView) snackbar.getView().findViewById(R.id.snackbar_text);
  Assertions.assertThat(messageView)
      .hasCompoundDrawablePadding(10);
  assertThat(messageView.getCompoundDrawables()[0]).isEqualTo(drawable);
}
 
Example 5
Source File: TwitterStaticNativeAdTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testStyleAttrsForDefaultTheme() {
    final TwitterStaticNativeAd nativeAd =
            new TwitterStaticNativeAd(RuntimeEnvironment.application);
    final int expectedContainerBgColor =
            nativeAd.getResources().getColor(R.color.tw__ad_light_container_bg_color);
    final int expectedCardBgColor =
            nativeAd.getResources().getColor(R.color.tw__ad_light_card_bg_color);
    final int expectedPrimaryTextColor =
            nativeAd.getResources().getColor(R.color.tw__ad_light_text_primary_color);
    final int ctaBackgroundColor =
            nativeAd.getResources().getColor(R.color.tw__ad_cta_default);
    final int cardBorderColor =
            nativeAd.getResources().getColor(R.color.tw__ad_light_card_border_color);

    assertEquals(expectedContainerBgColor, nativeAd.containerBackgroundColor);
    assertEquals(expectedCardBgColor, nativeAd.cardBackgroundColor);
    assertEquals(expectedPrimaryTextColor, nativeAd.primaryTextColor);
    assertEquals(ctaBackgroundColor, nativeAd.ctaBackgroundColor);
    assertEquals(cardBorderColor, nativeAd.cardBorderColor);
}
 
Example 6
Source File: PingerTest.java    From AndriodVideoCache with Apache License 2.0 5 votes vote down vote up
@Test // https://github.com/danikula/AndroidVideoCache/issues/28
public void testIsNotPingedWithoutCustomProxySelector() throws Exception {
    HttpProxyCacheServer server = new HttpProxyCacheServer(RuntimeEnvironment.application);
    // IgnoreHostProxySelector is set in HttpProxyCacheServer constructor. So let reset it by custom.
    installExternalSystemProxy();

    Pinger pinger = new Pinger("127.0.0.1", getPortWithoutPing(server));
    assertThat(pinger.ping(1, 100)).isFalse();
}
 
Example 7
Source File: LocalRepoKeyStoreTest.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testSignZip() throws IOException, LocalRepoKeyStore.InitException, IndexUpdater.SigningException {
    Context context = RuntimeEnvironment.application;

    File xmlIndexJarUnsigned = File.createTempFile(getClass().getName(), "unsigned.jar");
    BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(xmlIndexJarUnsigned));
    JarOutputStream jo = new JarOutputStream(bo);
    JarEntry je = new JarEntry(IndexUpdater.DATA_FILE_NAME);
    jo.putNextEntry(je);
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream("smallRepo.xml");
    IOUtils.copy(inputStream, jo);
    jo.close();
    bo.close();

    LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context);
    Certificate localCert = localRepoKeyStore.getCertificate();
    assertFalse(TextUtils.isEmpty(Utils.calcFingerprint(localCert)));

    File xmlIndexJar = File.createTempFile(getClass().getName(), IndexUpdater.SIGNED_FILE_NAME);
    localRepoKeyStore.signZip(xmlIndexJarUnsigned, xmlIndexJar);

    JarFile jarFile = new JarFile(xmlIndexJar, true);
    JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexUpdater.DATA_FILE_NAME);
    byte[] data = IOUtils.toByteArray(jarFile.getInputStream(indexEntry));
    assertEquals(17187, data.length);
    assertNotNull(IndexUpdater.getSigningCertFromJar(indexEntry));
}
 
Example 8
Source File: ProtocolTestBase.java    From dialogflow-android-client with Apache License 2.0 5 votes vote down vote up
@Test
public void sessionTest() throws AIServiceException {
    final AIConfiguration config = new AIConfiguration(getAccessToken(),
            AIConfiguration.SupportedLanguages.English,
            AIConfiguration.RecognitionEngine.System);

    updateConfig(config);

    final AIDataService firstService = new AIDataService(RuntimeEnvironment.application, config);
    final AIDataService secondService = new AIDataService(RuntimeEnvironment.application, config);

    {
        final AIRequest weatherRequest = new AIRequest();
        weatherRequest.setQuery("weather");
        final AIResponse weatherResponse = makeRequest(firstService, weatherRequest);
        assertNotNull(weatherResponse);
    }

    {
        final AIRequest checkSecondRequest = new AIRequest();
        checkSecondRequest.setQuery("check weather");
        final AIResponse checkSecondResponse = makeRequest(secondService, checkSecondRequest);
        assertNotNull(checkSecondResponse.getResult().getAction());
    }

    {
        final AIRequest checkFirstRequest = new AIRequest();
        checkFirstRequest.setQuery("check weather");
        final AIResponse checkFirstResponse = makeRequest(firstService, checkFirstRequest);
        assertNotNull(checkFirstResponse.getResult().getAction());
        assertTrue(checkFirstResponse.getResult().getAction().equalsIgnoreCase("checked"));
    }
}
 
Example 9
Source File: BaseTestCase.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    context = RuntimeEnvironment.application;
    config = new Config(generateConfigProperties());

    module = new CustomGuiceModule();
    glueInjections();
    // Set time zone to a constant value to make time-based tests predictable
    TimeZone.setDefault(TimeUtilsForTests.DEFAULT_TIME_ZONE);
    print("Started Test Case: " + getClass().getName());
}
 
Example 10
Source File: FabricReconcilerTest.java    From react-native-GPay with MIT License 5 votes vote down vote up
@Before
public void setUp() {
  CatalystInstance catalystInstance = ReactTestHelper.createMockCatalystInstance();
  ReactApplicationContext reactContext =
      new ReactApplicationContext(RuntimeEnvironment.application);
  reactContext.initializeWithInstance(catalystInstance);
  List<ViewManager> viewManagers = new ArrayList<>();
  ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers);
  JavaScriptContextHolder jsContext = mock(JavaScriptContextHolder.class);
  EventDispatcher eventDispatcher = mock(EventDispatcher.class);
  mFabricUIManager = new FabricUIManager(reactContext, viewManagerRegistry, jsContext, eventDispatcher);
  mMockUIViewOperationQueue = new MockUIViewOperationQueue(reactContext);
  mFabricReconciler = new FabricReconciler(mMockUIViewOperationQueue);
}
 
Example 11
Source File: AdActivityTest.java    From mobile-sdk-android with Apache License 2.0 5 votes vote down vote up
private void createBrowserActivity() {
    // creating AdActivity creates an implementation,
    // which consumes a webview
    WebView webView = new WebView(RuntimeEnvironment.application);
    BrowserAdActivity.BROWSER_QUEUE.add(webView);
    createActivity(AdActivity.ACTIVITY_TYPE_BROWSER);

    assertEquals(0, BrowserAdActivity.BROWSER_QUEUE.size());
}
 
Example 12
Source File: LeanplumPushServiceTest.java    From Leanplum-Android-SDK with Apache License 2.0 5 votes vote down vote up
/**
 * Runs before every test case.
 */
@Before
public void setUp() {
  mockStatic(LeanplumPushService.class);
  spy(LeanplumPushService.class);
  spy(Util.class);

  this.context = RuntimeEnvironment.application;
  assertNotNull(this.context);
  Leanplum.setApplicationContext(this.context);

  customizeNotificationBuilderCalled = false;
  customizeNotificationBuilderCompatCalled = false;
}
 
Example 13
Source File: QueryRequestActivityTest.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
/**
 * Launch query activity, fill out query prompts, make request, and store
 * result in session.  Checks request URL is built correctly.
 */
@Test
public void makeSuccessfulQueryRequestTest() {
    setSessionCommand("patient-search");

    ModernHttpRequesterMock.setResponseCodes(new Integer[]{200});
    ModernHttpRequesterMock.setExpectedUrls(
            new String[]{"https://www.fake.com/patient_search/?patient_id=123&name=francisco&device_id=000000000000000"});
    ModernHttpRequesterMock.setRequestPayloads(
            new String[]{"jr://resource/commcare-apps/case_search_and_claim/good-query-result.xml"});

    Intent queryActivityIntent =
            new Intent(RuntimeEnvironment.application, QueryRequestActivity.class);
    QueryRequestActivity queryRequestActivity =
            Robolectric.buildActivity(QueryRequestActivity.class, queryActivityIntent)
                    .setup().get();

    LinearLayout promptsLayout =
            queryRequestActivity.findViewById(R.id.query_prompts);
    EditText patientName = (EditText)promptsLayout.getChildAt(1);
    patientName.setText("francisco");
    EditText patientId = (EditText)promptsLayout.getChildAt(3);
    patientId.setText("123");

    Button queryButton = queryRequestActivity.findViewById(R.id.request_button);
    queryButton.performClick();

    assertEquals(Activity.RESULT_OK,
            Shadows.shadowOf(queryRequestActivity).getResultCode());
    assertTrue(queryRequestActivity.isFinishing());
}
 
Example 14
Source File: ProtoUtilsTest.java    From PainlessMusicPlayer with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadFromFileNonNullWhenNull() {
    final String fileName = "protoUtilsReadFromFileNonNullWhenNull";

    final Context context = RuntimeEnvironment.application;
    context.deleteFile(fileName);

    final SettingsProto.Settings read = ProtoUtils.readFromFileNonNull(
            context, fileName, new SettingsProto.Settings());
    assertNotNull(read);
}
 
Example 15
Source File: OverflowAreaBeaconTest.java    From android-beacon-library with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetectsOverfowAreadBeacon() {
    org.robolectric.shadows.ShadowLog.stream = System.err;
    Context context = RuntimeEnvironment.application;
    BeaconManager.getInstanceForApplication(context).setDebug(true);
    byte[] bytes = hexStringToByteArray("02011a020a0c0eff4c000f05a0336aa5f110025b0c14ff4c000156fe87490000000000000000000000000000000000000000000000000000000000000000");
    BeaconParser parser = new BeaconParser().setBeaconLayout("m:2-2=01,i:3-18,p:-:-59");
    Beacon beacon = parser.fromScanData(bytes, -55, null, 123456L);
    assertNotNull("beacon should be not null if parsed successfully", beacon);
    assertEquals("id should be parsed", "56fe8749-0000-0000-0000-000000000000", beacon.getId1().toString());
}
 
Example 16
Source File: ToastBuilderTest.java    From SnackbarBuilder with Apache License 2.0 5 votes vote down vote up
@Test
public void whenCustomView_thenCustomViewSet() {
  createBuilder();
  View customView = new View(RuntimeEnvironment.application);

  builderUnderTest.customView(customView);

  assertThat(builderUnderTest.customView).isEqualTo(customView);
}
 
Example 17
Source File: ContentObservablesTest.java    From agera with Apache License 2.0 4 votes vote down vote up
private static Application getApplication() {
  return RuntimeEnvironment.application;
}
 
Example 18
Source File: PreferenceStoreImplTest.java    From twitter-kit-android with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressLint("CommitPrefEdits")
public void testNamespace() {
    final String key = "Test namespace key";
    final String value = "Test namespace value";

    final PreferenceStoreImpl secondPrefStore =
            new PreferenceStoreImpl(RuntimeEnvironment.application, "PersistenceTest");

    assertNotSame(preferenceStore.get(), secondPrefStore.get());

    preferenceStore.save(preferenceStore.edit().putString(key, value));

    assertNull(secondPrefStore.get().getString(key, null));

}
 
Example 19
Source File: NetworkImageViewTest.java    From SaveVolley with Apache License 2.0 4 votes vote down vote up
@Before public void setUp() throws Exception {
    mMockImageLoader = new MockImageLoader();
    mNIV = new NetworkImageView(RuntimeEnvironment.application);
}
 
Example 20
Source File: CipherStorageKeystoreAesCbcTests.java    From react-native-keychain with MIT License 4 votes vote down vote up
private ReactApplicationContext getRNContext() {
  return new ReactApplicationContext(RuntimeEnvironment.application);
}