Java Code Examples for org.robolectric.RuntimeEnvironment

The following examples show how to use org.robolectric.RuntimeEnvironment. 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
Source Project: AndroidVideoCache   Source File: HttpProxyCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testReuseSourceInfo() throws Exception {
    SourceInfoStorage sourceInfoStorage = SourceInfoStorageFactory.newSourceInfoStorage(RuntimeEnvironment.application);
    HttpUrlSource source = new HttpUrlSource(HTTP_DATA_URL, sourceInfoStorage);
    File cacheFile = newCacheFile();
    HttpProxyCache proxyCache = new HttpProxyCache(source, new FileCache(cacheFile));
    processRequest(proxyCache, "GET /" + HTTP_DATA_URL + " HTTP/1.1");

    HttpUrlSource notOpenableSource = ProxyCacheTestUtils.newNotOpenableHttpUrlSource(HTTP_DATA_URL, sourceInfoStorage);
    HttpProxyCache proxyCache2 = new HttpProxyCache(notOpenableSource, new FileCache(cacheFile));
    Response response = processRequest(proxyCache2, "GET /" + HTTP_DATA_URL + " HTTP/1.1");
    proxyCache.shutdown();

    assertThat(response.data).isEqualTo(loadAssetFile(ASSETS_DATA_NAME));
    assertThat(response.contentLength).isEqualTo(HTTP_DATA_SIZE);
    assertThat(response.contentType).isEqualTo("image/jpeg");
}
 
Example 2
@Test
@Config(sdk = 24)
public void newChannelWithConnection_entersIdleOnSecondConnectionChange_api24() {
  shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED);
  TestChannel delegateChannel = new TestChannel();
  ManagedChannel androidChannel =
      new AndroidChannelBuilder.AndroidChannel(
          delegateChannel, RuntimeEnvironment.application.getApplicationContext());

  // The first onAvailable() may just signal that the device was connected when the callback is
  // registered, rather than indicating a changed network, so we do not enter idle.
  shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED);
  assertThat(delegateChannel.resetCount).isEqualTo(1);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(0);

  shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED);
  assertThat(delegateChannel.resetCount).isEqualTo(1);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(1);

  androidChannel.shutdown();
}
 
Example 3
@Test
@Config(sdk = 23)
public void shutdownNowUnregistersBroadcastReceiver_api23() {
  TestChannel delegateChannel = new TestChannel();
  ManagedChannel androidChannel =
      new AndroidChannelBuilder.AndroidChannel(
          delegateChannel, RuntimeEnvironment.application.getApplicationContext());

  shadowOf(connectivityManager).setActiveNetworkInfo(null);
  RuntimeEnvironment.application.sendBroadcast(
      new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
  androidChannel.shutdownNow();
  shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED);
  RuntimeEnvironment.application.sendBroadcast(
      new Intent(ConnectivityManager.CONNECTIVITY_ACTION));

  assertThat(delegateChannel.resetCount).isEqualTo(0);
}
 
Example 4
Source Project: weex-uikit   Source File: DefaultUriAdapterTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() {
  WXEnvironment.sApplication = RuntimeEnvironment.application;
  WXSDKManager wxsdkManager = WXSDKManager.getInstance();
  if (!new MockUtil().isSpy(wxsdkManager)) {
    WXSDKManager spy = Mockito.spy(wxsdkManager);
    WXSDKManagerTest.setInstance(spy);
    Mockito.when(spy.getIWXHttpAdapter()).thenReturn(new IWXHttpAdapter() {
      @Override
      public void sendRequest(WXRequest request, OnHttpListener listener) {
        //do nothing.
      }
    });
  }

  adapter = new DefaultUriAdapter();
  instance = WXSDKInstanceTest.createInstance();
}
 
Example 5
Source Project: PainlessMusicPlayer   Source File: BindingAdaptersTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSetFormattedDuration() {
    final TextView textView = new TextView(RuntimeEnvironment.application);
    assertEquals("", textView.getText());

    BindingAdapters.setFormattedDuration(textView, 0);
    assertEquals("0:00", textView.getText());

    BindingAdapters.setFormattedDuration(textView, 59);
    assertEquals("0:59", textView.getText());

    BindingAdapters.setFormattedDuration(textView, 60);
    assertEquals("1:00", textView.getText());

    BindingAdapters.setFormattedDuration(textView, 61);
    assertEquals("1:01", textView.getText());

    BindingAdapters.setFormattedDuration(textView, 3600);
    assertEquals("1:00:00", textView.getText());

    BindingAdapters.setFormattedDuration(textView, 3661);
    assertEquals("1:01:01", textView.getText());
}
 
Example 6
Source Project: PainlessMusicPlayer   Source File: ViewUtilsAndroidTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIsScrollableViewLargeEnoughToScrollWhenTrue() {
    final Context context = RuntimeEnvironment.application;
    final Pair<Integer, ViewGroup> heightsResult = prepareViewGroupWithValidChildHeights();

    final ViewGroup rootView = new FrameLayout(context);
    rootView.setBottom(heightsResult.first / 2);

    final ViewGroup appBarLayout = new FrameLayout(context);
    appBarLayout.setBottom(heightsResult.first / 2);

    final ViewGroup scrollableView = heightsResult.second;

    rootView.addView(appBarLayout);
    rootView.addView(scrollableView);

    assertTrue(ViewUtils.isScrollableViewLargeEnoughToScroll(rootView,
            appBarLayout,
            scrollableView,
            0));
}
 
Example 7
Source Project: firebase-android-sdk   Source File: UploadTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void fileUploadNoRecovery() throws Exception {
  System.out.println("Starting test fileUploadNoRecovery.");

  MockConnectionFactory factory =
      NetworkLayerMock.ensureNetworkMock("fileUploadNoRecovery", false);

  String filename = TEST_ASSET_ROOT + "flubbertest.jpg";
  ClassLoader classLoader = UploadTest.class.getClassLoader();
  InputStream imageStream = classLoader.getResourceAsStream(filename);
  Uri sourceFile = Uri.parse("file://" + filename);

  ContentResolver resolver =
      RuntimeEnvironment.application.getApplicationContext().getContentResolver();
  Shadows.shadowOf(resolver).registerInputStream(sourceFile, imageStream);

  Task<StringBuilder> task = TestUploadHelper.fileUpload(sourceFile, "flubbertest.jpg");

  TestUtil.await(task, 5, TimeUnit.SECONDS);

  factory.verifyOldMock();
  TestUtil.verifyTaskStateChanges("fileUploadNoRecovery", task.getResult().toString());
}
 
Example 8
Source Project: picasso   Source File: RequestCreatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void intoImageViewSetsPlaceholderWithResourceId() {
  PlatformLruCache cache = new PlatformLruCache(0);
  Picasso picasso =
      spy(new Picasso(RuntimeEnvironment.application, mock(Dispatcher.class), UNUSED_CALL_FACTORY,
          null, cache, null, NO_TRANSFORMERS, NO_HANDLERS, NO_EVENT_LISTENERS, ARGB_8888, false,
          false));
  ImageView target = mockImageViewTarget();
  new RequestCreator(picasso, URI_1, 0).placeholder(android.R.drawable.picture_frame)
      .into(target);
  ArgumentCaptor<Drawable> drawableCaptor = ArgumentCaptor.forClass(Drawable.class);
  verify(target).setImageDrawable(drawableCaptor.capture());
  assertThat(shadowOf(drawableCaptor.getValue()).getCreatedFromResId())
      .isEqualTo(android.R.drawable.picture_frame);
  verify(picasso).enqueueAndSubmit(actionCaptor.capture());
  assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class);
}
 
Example 9
Source Project: storio   Source File: InterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    final SQLiteOpenHelper sqLiteOpenHelper = new TestSQLiteOpenHelper(RuntimeEnvironment.application);

    callCount = new AtomicInteger(0);
    interceptor1 = createInterceptor();
    interceptor2 = createInterceptor();

    storIOSQLite = DefaultStorIOSQLite.builder()
            .sqliteOpenHelper(sqLiteOpenHelper)
            .addTypeMapping(Tweet.class, SQLiteTypeMapping.<Tweet>builder()
                    .putResolver(TweetTableMeta.PUT_RESOLVER)
                    .getResolver(TweetTableMeta.GET_RESOLVER)
                    .deleteResolver(TweetTableMeta.DELETE_RESOLVER)
                    .build())
            .addInterceptor(interceptor1)
            .addInterceptor(interceptor2)
            .build();
}
 
Example 10
@Test
public void decorate_whenOnline_shouldProperlyPopulateNetworkInfo() {
  CctTransportBackend backend =
      new CctTransportBackend(RuntimeEnvironment.application, wallClock, uptimeClock, 300);

  EventInternal result =
      backend.decorate(
          EventInternal.builder()
              .setEventMillis(INITIAL_WALL_TIME)
              .setUptimeMillis(INITIAL_UPTIME)
              .setTransportName("3")
              .setEncodedPayload(new EncodedPayload(PROTOBUF_ENCODING, PAYLOAD.toByteArray()))
              .build());

  assertThat(result.get(CctTransportBackend.KEY_NETWORK_TYPE))
      .isEqualTo(String.valueOf(NetworkConnectionInfo.NetworkType.MOBILE.getValue()));
  assertThat(result.get(CctTransportBackend.KEY_MOBILE_SUBTYPE))
      .isEqualTo(String.valueOf(NetworkConnectionInfo.MobileSubtype.EDGE.getValue()));
}
 
Example 11
Source Project: materialistic   Source File: WebFragmentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDownloadPdf() {
    ResolveInfo resolverInfo = new ResolveInfo();
    resolverInfo.activityInfo = new ActivityInfo();
    resolverInfo.activityInfo.applicationInfo = new ApplicationInfo();
    resolverInfo.activityInfo.applicationInfo.packageName = ListActivity.class.getPackage().getName();
    resolverInfo.activityInfo.name = ListActivity.class.getName();
    ShadowPackageManager rpm = shadowOf(RuntimeEnvironment.application.getPackageManager());
    when(item.getUrl()).thenReturn("http://example.com/file.pdf");
    rpm.addResolveInfoForIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(item.getUrl())), resolverInfo);

    WebView webView = activity.findViewById(R.id.web_view);
    ShadowWebView shadowWebView = Shadow.extract(webView);
    WebFragment fragment = (WebFragment) activity.getSupportFragmentManager()
            .findFragmentByTag(WebFragment.class.getName());
    shadowWebView.getDownloadListener().onDownloadStart(item.getUrl(), "", "", "application/pdf", 0L);
    shadowWebView.getWebViewClient().onPageFinished(webView, PDF_LOADER_URL);
    verify(fragment.mFileDownloader).downloadFile(
        eq(item.getUrl()),
        eq("application/pdf"),
        any(FileDownloader.FileDownloaderCallback.class));
}
 
Example 12
Source Project: rx-receivers   Source File: RxBatteryManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void batteryStateChanges() {
  Application application = RuntimeEnvironment.application;

  TestSubscriber<BatteryState> o = new TestSubscriber<>();
  RxBatteryManager.batteryChanges(application).subscribe(o);
  o.assertValues();

  Intent intent1 = new Intent(Intent.ACTION_BATTERY_CHANGED) //
      .putExtra(BatteryManager.EXTRA_HEALTH, BatteryManager.BATTERY_HEALTH_COLD)
      .putExtra(BatteryManager.EXTRA_ICON_SMALL, 0x3def2)
      .putExtra(BatteryManager.EXTRA_LEVEL, 10)
      .putExtra(BatteryManager.EXTRA_PLUGGED, 0)
      .putExtra(BatteryManager.EXTRA_PRESENT, true)
      .putExtra(BatteryManager.EXTRA_SCALE, 100)
      .putExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_CHARGING)
      .putExtra(BatteryManager.EXTRA_TECHNOLOGY, "unknown")
      .putExtra(BatteryManager.EXTRA_TEMPERATURE, 40)
      .putExtra(BatteryManager.EXTRA_VOLTAGE, 10000);
  application.sendBroadcast(intent1);
  BatteryState event1 =
      BatteryState.create(BatteryHealth.COLD, 0x3def2, 10, 0, true, 100,
          BatteryStatus.CHARGING, "unknown", 40, 10000);
  o.assertValues(event1);
}
 
Example 13
Source Project: braintree-android-drop-in   Source File: DropInActivityUnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void onPaymentMethodNonceCreated_requestsThreeDSecureVerificationForNonNetworkTokenizedGooglePayWhenEnabled()
        throws Exception {
    PackageManager packageManager = mockPackageManagerSupportsThreeDSecure();
    Context context = spy(RuntimeEnvironment.application);
    when(context.getPackageManager()).thenReturn(packageManager);
    mActivity.context = context;
    mActivity.setDropInRequest(new DropInRequest()
            .tokenizationKey(TOKENIZATION_KEY)
            .amount("1.00")
            .requestThreeDSecureVerification(true));
    mActivity.httpClient = spy(new BraintreeUnitTestHttpClient()
            .configuration(new TestConfigurationBuilder()
                    .threeDSecureEnabled(true)
                    .build()));
    mActivityController.setup();

    GooglePaymentCardNonce googlePaymentCardNonce = GooglePaymentCardNonce.fromJson(
            stringFromFixture("responses/google_pay_non_network_tokenized_response.json"));

    mActivity.onPaymentMethodNonceCreated(googlePaymentCardNonce);

    verify(mActivity.httpClient).post(matches(BraintreeUnitTestHttpClient.THREE_D_SECURE_LOOKUP),
            anyString(), any(HttpResponseCallback.class));
}
 
Example 14
Source Project: power-adapters   Source File: ConcatAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    mChildAdapters = newArrayList(
            spy(new FakeAdapter(3)),
            spy(new FakeAdapter(4)),
            spy(new FakeAdapter(5))
    );
    mConcatAdapter = new ConcatAdapterBuilder().addAll(mChildAdapters).build();
    mConcatAdapter.registerDataObserver(mObserver);
    mVerifyingObserver = new VerifyingAdapterObserver(mConcatAdapter);
    mConcatAdapter.registerDataObserver(mVerifyingObserver);
    for (PowerAdapter adapter : mChildAdapters) {
        verify(adapter).registerDataObserver(any(DataObserver.class));
        verify(adapter).onFirstObserverRegistered();
    }
    mParent = new FrameLayout(RuntimeEnvironment.application);
    mContainerViewGroup = new FrameLayout(RuntimeEnvironment.application);
    mItemView = new View(RuntimeEnvironment.application);
}
 
Example 15
@Test
public void testTrimFileCacheForTotalCountLru() throws Exception {
    FileNameGenerator fileNameGenerator = new Md5FileNameGenerator();
    HttpProxyCacheServer proxy = new HttpProxyCacheServer.Builder(RuntimeEnvironment.application)
            .cacheDirectory(cacheFolder)
            .fileNameGenerator(fileNameGenerator)
            .maxCacheFilesCount(2)
            .build();
    readProxyResponse(proxy, proxy.getProxyUrl(HTTP_DATA_URL), 0);
    assertThat(new File(cacheFolder, fileNameGenerator.generate(HTTP_DATA_URL))).exists();

    readProxyResponse(proxy, proxy.getProxyUrl(HTTP_DATA_URL_ONE_REDIRECT), 0);
    assertThat(new File(cacheFolder, fileNameGenerator.generate(HTTP_DATA_URL_ONE_REDIRECT))).exists();

    readProxyResponse(proxy, proxy.getProxyUrl(HTTP_DATA_URL_3_REDIRECTS), 0);
    assertThat(new File(cacheFolder, fileNameGenerator.generate(HTTP_DATA_URL_3_REDIRECTS))).exists();

    waitForAsyncTrimming();
    assertThat(new File(cacheFolder, fileNameGenerator.generate(HTTP_DATA_URL))).doesNotExist();
}
 
Example 16
@Before
public void setUp() throws Exception {
    preferenceStore = new PreferenceStoreImpl(RuntimeEnvironment.application, "testSession");
    mockSerializer = mock(SerializationStrategy.class);
    sessionMap = new ConcurrentHashMap<>();
    storageMap = new ConcurrentHashMap<>();
    mockActiveSessionStorage = mock(PreferenceStoreStrategy.class);
    sessionManager = new PersistedSessionManager<>(preferenceStore,
            mockSerializer, sessionMap, storageMap, mockActiveSessionStorage,
            PREF_KEY_SESSION);
}
 
Example 17
@Test
@Config(sdk = 24)
public void resetConnectBackoffAndEnterIdle_api24() {
  shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_DISCONNECTED);
  TestChannel delegateChannel = new TestChannel();
  ManagedChannel androidChannel =
      new AndroidChannelBuilder.AndroidChannel(
          delegateChannel, RuntimeEnvironment.application.getApplicationContext());
  assertThat(delegateChannel.resetCount).isEqualTo(0);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(0);

  // Establish an initial network connection
  shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED);
  assertThat(delegateChannel.resetCount).isEqualTo(1);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(0);

  // Switch to another network to trigger enterIdle()
  shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED);
  assertThat(delegateChannel.resetCount).isEqualTo(1);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(1);

  // Switch to an offline network and then to null
  shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_DISCONNECTED);
  shadowOf(connectivityManager).setActiveNetworkInfo(null);
  assertThat(delegateChannel.resetCount).isEqualTo(1);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(1);

  // Establish a connection
  shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED);
  assertThat(delegateChannel.resetCount).isEqualTo(2);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(1);

  // Disconnect, then shutdown the channel and verify that the callback has been unregistered
  shadowOf(connectivityManager).setActiveNetworkInfo(null);
  androidChannel.shutdown();
  shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED);

  assertThat(delegateChannel.resetCount).isEqualTo(2);
  assertThat(delegateChannel.enterIdleCount).isEqualTo(1);
}
 
Example 18
Source Project: braintree_android   Source File: CheckoutRequestUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void pairingId_setsClientMetadataId() {
    CheckoutRequest request = new CheckoutRequest()
            .pairingId(RuntimeEnvironment.application, "pairing-id");

    assertEquals("pairing-id", request.getClientMetadataId());
}
 
Example 19
@Test
public void testInitialValues() throws Exception {
  ShadowTrafficStats.setUidRxBytes(10000);
  ShadowTrafficStats.setUidTxBytes(20000);

  TrafficStatsNetworkBytesCollector collector =
      new TrafficStatsNetworkBytesCollector(RuntimeEnvironment.application);
  assertThat(collector.getTotalBytes(mBytes)).isTrue();
  assertThat(mBytes).isEqualTo(new long[] {0, 0, 10000, 20000, 0, 0, 0, 0});
}
 
Example 20
Source Project: braintree_android   Source File: AnalyticsDatabaseUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void addEvent_catchesSQLiteCantOpenDatabaseException() throws Exception {
    AnalyticsDatabase db = AnalyticsWithOpenExceptionsDatabase.getInstance(RuntimeEnvironment.application);
    AnalyticsEvent request = new AnalyticsEvent(RuntimeEnvironment.application, "sessionId",
            "custom", "started.client-token");

    db.addEvent(request);

    awaitTasksFinished(db);
}
 
Example 21
Source Project: braintree_android   Source File: ConfigurationManagerUnitTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() throws InvalidArgumentException {
    clearSharedPreferences(RuntimeEnvironment.application);
    ConfigurationManager.sFetchingConfiguration = false;
    mTokenizationKey = Authorization.fromString(TestTokenizationKey.TOKENIZATION_KEY);

    mCountDownLatch = new CountDownLatch(1);

    mBraintreeFragment = mock(BraintreeFragment.class);
    when(mBraintreeFragment.getAuthorization()).thenReturn(mTokenizationKey);
    when(mBraintreeFragment.getApplicationContext()).thenReturn(RuntimeEnvironment.application);
    when(mBraintreeFragment.getHttpClient()).thenReturn(new BraintreeHttpClient(mTokenizationKey));
}
 
Example 22
Source Project: Emoji   Source File: VariantEmojiManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before public void setUp() {
  variantEmojiManager = new VariantEmojiManager(RuntimeEnvironment.application);

  emoji = new Emoji(0x1f437, R.drawable.emoji_recent, false);
  variant1 = new Emoji(0x1f55b, R.drawable.emoji_recent, false);
  variant2 = new Emoji(0x1f55c, R.drawable.emoji_recent, false);
  variant3 = new Emoji(0x1f55d, R.drawable.emoji_recent, false);
  base = new Emoji(0x1f55a, R.drawable.emoji_recent, false, variant1, variant2, variant3);
}
 
Example 23
Source Project: RIBs   Source File: RibActivityTest.java    License: Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
protected ViewRouter<?, ?, ?> createRouter(@NonNull ViewGroup parentViewGroup) {
  FrameLayout view = new FrameLayout(RuntimeEnvironment.application);

  InteractorComponent component = mock(InteractorComponent.class);
  ViewPresenter presenter = new ViewPresenter<View>(view) {};
  when(component.presenter()).thenReturn(presenter);

  return new EmptyRouter(view, new TestInteractor(), component);
}
 
Example 24
Source Project: ucar-weex-core   Source File: WXDomStatementTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  WXSDKEngine.initialize(RuntimeEnvironment.application,new InitConfig.Builder().build());
  ShadowLooper looper = WXBridgeManagerTest.getLooper();
  looper.idle();
  ShadowLooper.runUiThreadTasksIncludingDelayedTasks();
  instance = WXSDKInstanceTest.createInstance();
  rednerManager = new WXRenderManager();
  rednerManager.registerInstance(instance);//
  WXSDKManagerTest.setRenderManager(rednerManager);
  stmt = new DOMActionContextImpl(instance.getInstanceId(),rednerManager );
}
 
Example 25
Source Project: ucar-weex-core   Source File: WXDivTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddChild(){
    WXSDKInstance instance = Mockito.mock(WXSDKInstance.class);
    Mockito.when(instance.getContext()).thenReturn(RuntimeEnvironment.application);

    WXDomObject testDom = Mockito.mock(WXDomObject.class);
    Mockito.when(testDom.getPadding()).thenReturn(new Spacing());
    Mockito.when(testDom.clone()).thenReturn(testDom);
    TestDomObject.setRef(testDom,"2");
    WXText child1 = new WXText(instance, testDom, mWXDiv);
    child1.initView();

    mWXDiv.addChild(child1, 0);

    assertEquals(1, mWXDiv.childCount());

    WXDomObject testDom2 = Mockito.spy(new WXDomObject());
    Mockito.when(testDom2.getPadding()).thenReturn(new Spacing());
    Mockito.when(testDom2.clone()).thenReturn(testDom2);
    TestDomObject.setRef(testDom2,"3");
    child2 = new WXText(instance, testDom2, mWXDiv);
    child2.initView();

    mWXDiv.addChild(child2, -1);

    assertEquals(2, mWXDiv.childCount());
    assertEquals(child2, mWXDiv.getChild(1));

    WXDomObject testDom3 = Mockito.mock(WXDomObject.class);
    Mockito.when(testDom3.getPadding()).thenReturn(new Spacing());
    Mockito.when(testDom3.clone()).thenReturn(testDom3);
    TestDomObject.setRef(testDom3,"4");
    WXText child3 = new WXText(instance, testDom3, mWXDiv);
    child3.initView();

    mWXDiv.addChild(child3, 1);

    assertEquals(3, mWXDiv.childCount());
    assertEquals(child3, mWXDiv.getChild(1));
}
 
Example 26
Source Project: sensey   Source File: SenseyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    Context context = RuntimeEnvironment.application.getApplicationContext();
    shadowSensorManager =
            Shadows.shadowOf((SensorManager) context.getSystemService(SENSOR_SERVICE));

    sensey = Sensey.getInstance();
    sensey.init(context);
}
 
Example 27
Source Project: firebase-android-sdk   Source File: SchedulerConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void configureJob_whenUnmetered_shouldSetCorrectFlags() {
  ComponentName serviceComponent =
      new ComponentName(RuntimeEnvironment.application, JobInfoSchedulerService.class);
  SchedulerConfig config = createConfig(EnumSet.of(SchedulerConfig.Flag.NETWORK_UNMETERED));

  JobInfo job =
      config
          .configureJob(new JobInfo.Builder(1, serviceComponent), Priority.DEFAULT, 0, 1)
          .build();

  assertThat(job.getNetworkType()).isEqualTo(JobInfo.NETWORK_TYPE_UNMETERED);
  assertThat(job.isRequireDeviceIdle()).isFalse();
  assertThat(job.isRequireCharging()).isFalse();
}
 
Example 28
Source Project: OpenYOLO-Android   Source File: ProviderResolverTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    saveIntent = new Intent(ProtocolConstants.SAVE_CREDENTIAL_ACTION);
    saveIntent.addCategory(ProtocolConstants.OPENYOLO_CATEGORY);

    shadowPackageManager =
            Shadows.shadowOf(RuntimeEnvironment.application.getPackageManager());
}
 
Example 29
Source Project: materialistic   Source File: WidgetProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Config(sdk = 18)
@Test
public void testAlarmAfterReboot() {
    // rebooting should update widget again via update broadcast
    widgetProvider.onReceive(RuntimeEnvironment.application,
            new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
                    .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[]{appWidgetId}));
    assertThat(shadowOf(alarmManager).getNextScheduledAlarm()).isNotNull();
    widgetProvider.onDeleted(RuntimeEnvironment.application, new int[]{appWidgetId});
    assertThat(shadowOf(alarmManager).getNextScheduledAlarm()).isNull();
}
 
Example 30
Source Project: picasso   Source File: RequestCreatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void intoImageViewNoPlaceholderDrawable() {
  PlatformLruCache cache = new PlatformLruCache(0);
  Picasso picasso =
      spy(new Picasso(RuntimeEnvironment.application, mock(Dispatcher.class), UNUSED_CALL_FACTORY,
          null, cache, null, NO_TRANSFORMERS, NO_HANDLERS, NO_EVENT_LISTENERS, ARGB_8888, false,
          false));
  ImageView target = mockImageViewTarget();
  new RequestCreator(picasso, URI_1, 0).noPlaceholder().into(target);
  verifyNoMoreInteractions(target);
  verify(picasso).enqueueAndSubmit(actionCaptor.capture());
  assertThat(actionCaptor.getValue()).isInstanceOf(ImageViewAction.class);
}