@Implementation
 public static Camera open(int cameraId) {
   lastOpenedCameraId = cameraId;
   Camera camera = Robolectric.newInstanceOf(Camera.class);
   Robolectric.shadowOf(camera).id = cameraId;
   return camera;
 }
  @Test
  public void loadAd_whenCallingOnBannerFailed_shouldCancelExistingTimeoutRunnable()
      throws Exception {
    Robolectric.pauseMainLooper();

    Answer justCallOnBannerFailed =
        new Answer() {
          @Override
          public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(1);
            subject.onBannerFailed(null);
            assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);
            return null;
          }
        };

    doAnswer(justCallOnBannerFailed)
        .when(banner)
        .loadBanner(
            any(Context.class),
            any(CustomEventBanner.CustomEventBannerListener.class),
            any(Map.class),
            any(Map.class));

    assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);
    subject.loadAd();
    assertThat(Robolectric.getUiThreadScheduler().enqueuedTaskCount()).isEqualTo(0);
  }
  @Test
  public void getNextSentHttpRequest_shouldRemoveHttpRequests() throws Exception {
    Robolectric.addPendingHttpResponse(200, "a happy response body");
    HttpGet httpGet = new HttpGet("http://example.com");
    requestDirector.execute(null, httpGet, null);

    assertSame(Robolectric.getNextSentHttpRequest(), httpGet);
    assertNull(Robolectric.getNextSentHttpRequest());
  }
Example #4
0
  @Test
  public void skipLoginAndCancel() {
    ShadowActivity shadowActivity = Robolectric.shadowOf(loginActivity);

    ((TextView) loginActivity.findViewById(R.id.skipLogin)).performClick();
    AlertDialog latestAlertDialog = ShadowAlertDialog.getLatestAlertDialog();
    ShadowAlertDialog dialog = Robolectric.shadowOf(latestAlertDialog);
    assertEquals(loginActivity.getString(R.string.noLoginWarn), dialog.getMessage());
    assertTrue(latestAlertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick());
    assertNull(shadowActivity.getNextStartedActivity());
  }
  @Test
  public void shouldQueueUiTasksWhenUiThreadIsPaused() throws Exception {
    Robolectric.pauseMainLooper();

    activity = create(DialogLifeCycleActivity.class);
    TestRunnable runnable = new TestRunnable();
    activity.runOnUiThread(runnable);
    assertFalse(runnable.wasRun);

    Robolectric.unPauseMainLooper();
    assertTrue(runnable.wasRun);
  }
  @Test
  public void clearPendingHttpResponses() throws Exception {
    Robolectric.addPendingHttpResponse(200, "earlier");
    Robolectric.clearPendingHttpResponses();
    Robolectric.addPendingHttpResponse(500, "later");

    HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);

    assertNotNull(response);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(500));
    assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("later"));
  }
Example #7
0
  @Test(expected = IllegalArgumentException.class)
  public void shouldNotBeAbleToExitTheWrongScope() {
    final ContextScope scope =
        RoboGuice.getOrCreateBaseApplicationInjector(Robolectric.application)
            .getInstance(ContextScope.class);
    final Activity a = Robolectric.buildActivity(A.class).get();
    final Activity b = Robolectric.buildActivity(B.class).get();

    scope.enter(a);
    scope.enter(b);
    scope.exit(a);
  }
  @Test
  public void timeout_shouldSignalFailureAndInvalidateWithDefaultDelay() throws Exception {
    subject.loadAd();

    Robolectric.idleMainLooper(CustomEventBannerAdapter.DEFAULT_BANNER_TIMEOUT_DELAY - 1);
    verify(moPubView, never()).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isFalse();

    Robolectric.idleMainLooper(1);
    verify(moPubView).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isTrue();
  }
  @Test
  public void shouldSupportRealHttpRequestsAddingRequestInfo() throws Exception {
    Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
    DefaultHttpClient client = new DefaultHttpClient();

    // it's really bad to depend on an external server in order to get a test pass,
    // but this test is about making sure that we can intercept calls to external servers
    // so, I think that in this specific case, it's appropriate...
    client.execute(new HttpGet("http://google.com"));

    assertNotNull(Robolectric.getFakeHttpLayer().getLastSentHttpRequestInfo());
    assertNotNull(Robolectric.getFakeHttpLayer().getLastHttpResponse());
  }
  @Test
  public void shouldRecordExtendedRequestData() throws Exception {
    Robolectric.addPendingHttpResponse(200, "a happy response body");
    HttpGet httpGet = new HttpGet("http://example.com");
    requestDirector.execute(null, httpGet, null);

    assertSame(Robolectric.getSentHttpRequestInfo(0).getHttpRequest(), httpGet);
    ConnectionKeepAliveStrategy strategy =
        shadowOf(
                (DefaultRequestDirector) Robolectric.getSentHttpRequestInfo(0).getRequestDirector())
            .getConnectionKeepAliveStrategy();
    assertSame(strategy, connectionKeepAliveStrategy);
  }
  @Test
  public void clearHttpResponseRules_shouldRemoveAllRules() throws Exception {
    Robolectric.addHttpResponseRule("http://some.uri", "a cheery response body");
    Robolectric.clearHttpResponseRules();
    Robolectric.addHttpResponseRule("http://some.uri", "a gloomy response body");

    HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);

    assertNotNull(response);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(
        Strings.fromStream(response.getEntity().getContent()), equalTo("a gloomy response body"));
  }
  @Test
  public void shouldReturnRequestsByRule_MatchingMethod() throws Exception {
    Robolectric.setDefaultHttpResponse(404, "no such page");
    Robolectric.addHttpResponseRule(
        HttpPost.METHOD_NAME,
        "http://some.uri",
        new TestHttpResponse(200, "a cheery response body"));

    HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);

    assertNotNull(response);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
  }
Example #13
0
  @Test
  public void shouldBeAbleToOpenMultipleScopes() {
    final ContextScope scope =
        RoboGuice.getOrCreateBaseApplicationInjector(Robolectric.application)
            .getInstance(ContextScope.class);
    final Activity a = Robolectric.buildActivity(A.class).get();
    final Activity b = Robolectric.buildActivity(B.class).get();

    scope.enter(a);
    scope.enter(b);
    scope.exit(b);
    scope.exit(a);
  }
@RunWith(TestRunners.WithDefaults.class)
public class SurfaceViewTest {

  private SurfaceHolder.Callback callback1 = new TestCallback();
  private SurfaceHolder.Callback callback2 = new TestCallback();

  private SurfaceView view =
      new SurfaceView(Robolectric.buildActivity(Activity.class).create().get());
  private SurfaceHolder surfaceHolder = view.getHolder();
  private ShadowSurfaceView shadowSurfaceView = (ShadowSurfaceView) Robolectric.shadowOf(view);
  private ShadowSurfaceView.FakeSurfaceHolder fakeSurfaceHolder =
      shadowSurfaceView.getFakeSurfaceHolder();

  @Test
  public void addCallback() {
    assertThat(fakeSurfaceHolder.getCallbacks()).isEmpty();

    surfaceHolder.addCallback(callback1);

    assertThat(fakeSurfaceHolder.getCallbacks()).contains(callback1);

    surfaceHolder.addCallback(callback2);

    assertThat(fakeSurfaceHolder.getCallbacks()).contains(callback1);
    assertThat(fakeSurfaceHolder.getCallbacks()).contains(callback2);
  }

  @Test
  public void removeCallback() {
    surfaceHolder.addCallback(callback1);
    surfaceHolder.addCallback(callback2);

    assertThat(fakeSurfaceHolder.getCallbacks().size()).isEqualTo(2);

    surfaceHolder.removeCallback(callback1);

    assertThat(fakeSurfaceHolder.getCallbacks()).doesNotContain(callback1);
    assertThat(fakeSurfaceHolder.getCallbacks()).contains(callback2);
  }

  private static class TestCallback implements SurfaceHolder.Callback {
    @Override
    public void surfaceCreated(SurfaceHolder holder) {}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {}

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {}
  }
}
  @Test
  public void timeout_withNonNullAdTimeoutDelay_shouldSignalFailureAndInvalidateWithCustomDelay()
      throws Exception {
    stub(moPubView.getAdTimeoutDelay()).toReturn(77);

    subject.loadAd();

    Robolectric.idleMainLooper(77000 - 1);
    verify(moPubView, never()).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isFalse();

    Robolectric.idleMainLooper(1);
    verify(moPubView).loadFailUrl(eq(NETWORK_TIMEOUT));
    assertThat(subject.isInvalidated()).isTrue();
  }
  @Test
  public void shouldFindLastRequestMade() throws Exception {
    Robolectric.addPendingHttpResponse(200, "a happy response body");
    Robolectric.addPendingHttpResponse(200, "a happy response body");
    Robolectric.addPendingHttpResponse(200, "a happy response body");

    DefaultHttpClient client = new DefaultHttpClient();
    client.execute(new HttpGet("http://www.first.org"));
    client.execute(new HttpGet("http://www.second.org"));
    client.execute(new HttpGet("http://www.third.org"));

    assertThat(
        ((HttpUriRequest) Robolectric.getLatestSentHttpRequest()).getURI(),
        equalTo(URI.create("http://www.third.org")));
  }
  @Test
  public void shouldSupportBasicResponseHandlerHandleResponse() throws Exception {
    Robolectric.addPendingHttpResponse(200, "OK", new BasicHeader("Content-Type", "text/plain"));

    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(new HttpGet("http://www.nowhere.org"));

    assertThat(
        ((HttpUriRequest) Robolectric.getSentHttpRequest(0)).getURI(),
        equalTo(URI.create("http://www.nowhere.org")));

    Assert.assertNotNull(response);
    String responseStr = new BasicResponseHandler().handleResponse(response);
    Assert.assertEquals("OK", responseStr);
  }
  @Test
  public void execute_whenUberAppInsalled_shouldPointToUberApp() throws IOException {
    String expectedUri =
        readUriResourceWithUserAgentParam(
            "src/test/resources/deeplinkuris/just_client_provided", USER_AGENT_DEEPLINK);

    Activity activity = Robolectric.setupActivity(Activity.class);
    ShadowActivity shadowActivity = shadowOf(activity);

    RobolectricPackageManager packageManager =
        (RobolectricPackageManager) shadowActivity.getPackageManager();

    PackageInfo uberPackage = new PackageInfo();
    uberPackage.packageName = UBER_PACKAGE_NAME;
    packageManager.addPackage(uberPackage);

    RideParameters rideParameters = new RideParameters.Builder().build();

    RequestDeeplink requestDeeplink =
        new RequestDeeplink.Builder()
            .setClientId(CLIENT_ID)
            .setRideParameters(rideParameters)
            .build();

    requestDeeplink.execute(activity);

    Intent startedIntent = shadowActivity.getNextStartedActivity();
    assertEquals(expectedUri, startedIntent.getData().toString());
  }
 @Implementation
 public static CookieManager getInstance() {
   if (sRef == null) {
     sRef = Robolectric.newInstanceOf(CookieManager.class);
   }
   return sRef;
 }
  @Test
  public void deveAtualizarEstadoListaItemsCardapio() {

    Marmitaria m =
        new MarmitariaBuilder()
            .newMarmitaria("camilo", "12345", "tereza campos")
            .criaCardapio("Segunda-Feira")
            .adicioneGrupo("Carnes")
            .comOpcao("Patinho")
            .comOpcao("Frango Grelhado")
            .ok()
            .adicioneGrupo("Acompanhamentos")
            .comOpcao("Feijao")
            .comOpcao("Arroz")
            .ok()
            .adicioneGrupo("Salada")
            .comOpcao("Hortaliças")
            .comOpcao("Legumes no Vapor")
            .ok()
            .okCardapio()
            .getMarmitaria();

    Intent i = new Intent(RuntimeEnvironment.application, GrupoOpcaoCardapioActivity.class);
    i.putExtra(GrupoOpcaoListFragment.ARG_NAME_CARDAPIO, m.getCardapios().get(0));

    GrupoOpcaoCardapioActivity grupoOpcaoCardapioActivity =
        Robolectric.buildActivity(GrupoOpcaoCardapioActivity.class).withIntent(i).visible().get();

    // FIXME terminar este teste

  }
Example #21
0
 @Ignore // todo we need to figure out a better way to deal with this...
 @Test // the shadow will still have its default constructor called; it would be duplicative to
       // call __constructor__() too.
 @Config(shadows = {ShadowForClassWithNoDefaultConstructor.class})
 public void forClassWithNoDefaultConstructor_generatedDefaultConstructorShouldNotCallShadow()
     throws Exception {
   Constructor<ClassWithNoDefaultConstructor> ctor =
       ClassWithNoDefaultConstructor.class.getDeclaredConstructor();
   ctor.setAccessible(true);
   ClassWithNoDefaultConstructor instance = ctor.newInstance();
   assertThat(Robolectric.shadowOf_(instance)).isNotNull();
   assertThat(Robolectric.shadowOf_(instance))
       .isInstanceOf(ShadowForClassWithNoDefaultConstructor.class);
   assertTrue(ShadowForClassWithNoDefaultConstructor.shadowDefaultConstructorCalled);
   assertFalse(ShadowForClassWithNoDefaultConstructor.shadowDefaultConstructorImplementorCalled);
 }
@RunWith(RobolectricTestRunner.class)
public class RefereeActivityTest {

  private final Referee referee = Robolectric.buildActivity(Referee.class).create().get();
  private final Button player1Score = (Button) referee.findViewById(R.id.player1Score);
  private final TextView scoreView = (TextView) referee.findViewById(R.id.scoreView);

  @Test
  public void display_Love_All_as_init_score() {
    assertEquals("Love All", scoreView.getText().toString());
  }

  @Test
  public void fifteen_love_after_player1_scores() {
    player1Score.performClick();

    assertEquals("Fifteen Love", scoreView.getText().toString());
  }

  @Test
  public void Thirty_Love_after_player1_scores_twice() {
    player1Score.performClick();
    player1Score.performClick();

    assertEquals("Thirty Love", scoreView.getText().toString());
  }
}
  /** - 内容:sendInBackground(POST)が成功することを確認する - 結果:非同期でプッシュの送信が出来る事 */
  @Test
  public void sendInBackground_post() throws Exception {
    Assert.assertFalse(callbackFlag);
    // post
    NCMBPush push = new NCMBPush();
    push.setMessage("message");
    push.setTitle("title");
    push.sendInBackground(
        new DoneCallback() {

          @Override
          public void done(NCMBException e) {
            Assert.assertNull(e);
            callbackFlag = true;
          }
        });

    Robolectric.flushBackgroundThreadScheduler();
    ShadowLooper.runUiThreadTasks();

    Assert.assertTrue(callbackFlag);

    // check
    Assert.assertEquals("message", push.getMessage());
    Assert.assertEquals("title", push.getTitle());
    Assert.assertEquals("7FrmPTBKSNtVjajm", push.getObjectId());
    DateFormat format = NCMBDateFormat.getIso8601();
    Assert.assertEquals(format.parse("2014-06-03T11:28:30.348Z"), push.getCreateDate());
  }
 @Test
 public void getActionBar_shouldWorkIfActivityHasAnAppropriateTheme() throws Exception {
   ActionBarThemedActivity myActivity =
       Robolectric.buildActivity(ActionBarThemedActivity.class).create().get();
   ActionBar actionBar = myActivity.getActionBar();
   assertThat(actionBar).isNotNull();
 }
  @Test
  public void shouldAllowBackgroundThreadsToFinishUsingContextAfterOnDestroy() throws Exception {
    final SoftReference<F> ref =
        new SoftReference<F>(Robolectric.buildActivity(F.class).create().get());

    final BlockingQueue<Context> queue = new ArrayBlockingQueue<Context>(1);
    new Thread() {
      final Context context = RoboGuice.getInjector(ref.get()).getInstance(Context.class);

      @Override
      public void run() {
        queue.add(context);
      }
    }.start();

    ref.get().onDestroy();

    // Force an OoM
    // http://stackoverflow.com/questions/3785713/how-to-make-the-java-system-release-soft-references/3810234
    boolean oomHappened = false;
    try {
      @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"})
      final ArrayList<Object[]> allocations = new ArrayList<Object[]>();
      int size;
      while ((size = Math.min(Math.abs((int) Runtime.getRuntime().freeMemory()), Integer.MAX_VALUE))
          > 0) allocations.add(new Object[size]);

    } catch (OutOfMemoryError e) {
      // Yeah!
      oomHappened = true;
    }

    assertTrue(oomHappened);
    assertNotNull(queue.poll(10, TimeUnit.SECONDS));
  }
 @Before
 public void prepare() {
   ActivityController<MainActivity_> activityController =
       Robolectric.buildActivity(MainActivity_.class);
   activityController.create();
   activity = activityController.get();
 }
  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    Mockito.stub(mPhotoListManager.getPhotoListFetched()).toReturn(true);

    activityController = Robolectric.buildActivity(PhotosListViewActivity.class);
    subject = activityController.get();
    Mockito.doAnswer(
            new Answer() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                subject.requestPermissionCallback.Granted(1);
                return null;
              }
            })
        .when(mRequestPermissionUtils)
        .requestPermission(
            subject,
            Manifest.permission.ACCESS_FINE_LOCATION,
            subject.requestPermissionCallback,
            Constants.MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    flickrPhotoList =
        new ArrayList<FlickrPhoto>(
            Arrays.asList(new FlickrPhoto("some-photo", "some-small-url", "some-big-url")));
    subject.setFlickrPhotoList(flickrPhotoList);
    activityController.create().start();
  }
Example #28
0
 @Test
 public void onResume_shouldRegisterFindMeReceiver() {
   Intent expectedIntent = new Intent(COM_MAPZEN_FIND_ME);
   List<BroadcastReceiver> findMeReceivers =
       Robolectric.getShadowApplication().getReceiversForIntent(expectedIntent);
   assertThat(findMeReceivers).hasSize(1);
 }
  /** - 内容:executeScriptInBackgroundが成功することを確認する - 結果:エラーが発生しないこと */
  @Test
  public void executeScriptInBackground() throws Exception {
    NCMBScriptService scriptService = (NCMBScriptService) NCMB.factory(NCMB.ServiceType.SCRIPT);
    scriptService.executeScriptInBackground(
        "testScript.js",
        NCMBScript.MethodType.GET,
        null,
        null,
        null,
        mScriptUrl,
        new ExecuteScriptCallback() {
          @Override
          public void done(byte[] result, NCMBException e) {
            if (e != null) {
              Assert.fail(e.getMessage());
            } else {
              try {
                Assert.assertEquals("hello", new String(result, "UTF-8"));
              } catch (UnsupportedEncodingException error) {
                Assert.fail(error.getMessage());
              }
            }
            mCallbackFlag = true;
          }
        });

    Robolectric.flushBackgroundThreadScheduler();
    ShadowLooper.runUiThreadTasks();

    Assert.assertTrue(mCallbackFlag);
  }
 @Test
 public void viewPager_CurrentPage() {
   MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class);
   ViewPager viewPager = (ViewPager) mainActivity.findViewById(R.id.viewPager);
   assertEquals(viewPager.getCurrentItem(), 2);
   assertEquals(viewPager.getAdapter().getPageTitle(2).toString(), "Today");
 }