Пример #1
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);
  }
Пример #2
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);
  }
  @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();
  }
Пример #4
0
 @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 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

  }
@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());
  }
}
  @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));
  }
Пример #8
0
 @Before
 public void prepare() {
   ActivityController<MainActivity_> activityController =
       Robolectric.buildActivity(MainActivity_.class);
   activityController.create();
   activity = activityController.get();
 }
  @Test
  public void testOnCreateWhenASKEnabledAndInactive() throws Exception {
    // mocking ASK as enable and inactive
    ShadowSettings.ShadowSecure.putString(
        RuntimeEnvironment.application.getContentResolver(),
        Settings.Secure.ENABLED_INPUT_METHODS,
        new ComponentName("net.some.one.else", "net.some.one.else.IME").flattenToString()
            + ":"
            + new ComponentName(
                    RuntimeEnvironment.application.getPackageName(),
                    RuntimeEnvironment.application.getPackageName() + ".IME")
                .flattenToString());
    ShadowSettings.ShadowSecure.putString(
        RuntimeEnvironment.application.getContentResolver(),
        Settings.Secure.DEFAULT_INPUT_METHOD,
        new ComponentName("net.some.one.else", "net.some.one.else.IME").flattenToString());

    Assert.assertNull(ShadowApplication.getInstance().getNextStartedActivity());
    ActivityController<LauncherSettingsActivity> controller =
        Robolectric.buildActivity(LauncherSettingsActivity.class).attach().create().resume();
    Intent startMainApp = ShadowApplication.getInstance().getNextStartedActivity();
    Assert.assertNotNull(startMainApp);

    Intent expectIntent = new Intent(controller.get(), MainSettingsActivity.class);

    Assert.assertEquals(expectIntent.getComponent(), startMainApp.getComponent());
  }
Пример #10
0
 @Before
 public void setUp() throws Exception {
   this.clothe();
   Intent intent = this.createIntent();
   this.activityMail =
       Robolectric.buildActivity(ActivityMail.class).withIntent(intent).create().visible().get();
 }
Пример #11
0
  @Test // unclear what the correct behavior should be here...
  public void shouldPopulateWindowDecorViewWithMergeLayoutContents() throws Exception {
    Activity activity = Robolectric.buildActivity(Activity.class).create().get();
    activity.setContentView(R.layout.toplevel_merge);

    View contentView = activity.findViewById(android.R.id.content);
    assertThat(((ViewGroup) contentView).getChildCount()).isEqualTo(2);
  }
Пример #12
0
 /**
  * Starts a fragment on the Activity specified by activityClass. Before calling it, set any
  * defaults you need on your activity. Unlike the Robolectric implementation, this also calls
  * visible() on the activity.
  *
  * @activityClass the activity class you want the fragment added to
  * @param fragment
  * @param tag the tag with which it adds the fragment. If null, defaults to {@link
  *     TestConstants#DEFAULT_FRAGMENT_TAG}
  */
 public static <T extends Activity> void startFragmentForActivity(
     Class<T> activityClass, Fragment fragment, String tag) {
   if (tag == null) {
     tag = TestConstants.DEFAULT_FRAGMENT_TAG;
   }
   Activity activity = Robolectric.buildActivity(activityClass).create().start().resume().get();
   startFragmentHelper(activity, fragment, tag, true);
 }
Пример #13
0
 @Before
 public void setUp() {
   MainActivity mainActivity = Robolectric.buildActivity(MainActivity.class).create().get();
   assertNotNull("Main Activity not setup", mainActivity);
   listView = (ListView) mainActivity.findViewById(R.id.list_of_signs);
   zodiacSigns =
       RuntimeEnvironment.application.getResources().getStringArray(R.array.zodiac_array);
 }
  @Test
  public void testJustFinishIfCreatedAgain() throws Exception {
    ActivityController<LauncherSettingsActivity> controller =
        Robolectric.buildActivity(LauncherSettingsActivity.class).attach().create().resume();
    ShadowActivity shadowActivity = Shadows.shadowOf(controller.get());
    Assert.assertFalse(shadowActivity.isFinishing());
    controller.pause().stop();
    Assert.assertFalse(shadowActivity.isFinishing());
    Bundle state = new Bundle();
    controller.saveInstanceState(state).destroy();

    controller = Robolectric.buildActivity(LauncherSettingsActivity.class).attach().create(state);
    shadowActivity = Shadows.shadowOf(controller.get());
    Assert.assertFalse(shadowActivity.isFinishing());
    controller.resume();
    Assert.assertTrue(shadowActivity.isFinishing());
  }
Пример #15
0
  @Test
  public void verifyNotRequiredExtraBinding() {
    SimpleFragmentActivity activity =
        Robolectric.buildActivity(SimpleFragmentActivity.class).create().get();

    assertEquals(2, activity.intExtra);
    assertEquals("NOT_REQUIRED", activity.stringExtra);
  }
  @Before
  public void setUp() {
    mActivityController = Robolectric.buildActivity(MainActivity.class).create().start().resume();

    mActivity = mActivityController.get();
    sut = WordDetailsTranslationFragment.newInstance(TestHelper.createWord(), 1);

    SupportFragmentTestUtil.startVisibleFragment(sut);
  }
 @Test(expected = ConfigurationException.class)
 public void shouldNotStaticallyInjectPreferenceViews() {
   RoboGuice.setBaseApplicationInjector(
       Robolectric.application,
       Stage.DEVELOPMENT,
       RoboGuice.newDefaultRoboModule(Robolectric.application),
       new ModuleC());
   @SuppressWarnings("unused")
   final C c = Robolectric.buildActivity(C.class).create().get();
 }
Пример #18
0
  @Before
  public void setUp() throws Exception {
    activity = Robolectric.buildActivity(Activity.class).create().get();
    listener =
        new TextToSpeech.OnInitListener() {
          @Override
          public void onInit(int i) {}
        };

    textToSpeech = new TextToSpeech(activity, listener);
  }
 public void setup() {
   APSDKSetup.setDBStoreType(DBStoreType.IN_MEMORY);
   com.anypresence.rails_droid.RemoteRailsConfig.DEBUG = true;
   if (context == null) {
     context = Robolectric.buildActivity(MyActivity.class).attach().create().get();
     APSetup.setBaseUrl("http://localhost");
     APSetup.setup();
     Config.TEST_MODE = true;
     APSetup.setupOrm(context);
   }
 }
Пример #20
0
  @Test
  public void check_drawer_menu_settings_item() throws Exception {
    MainActivity activity = Robolectric.buildActivity(MainActivity.class).create().get();

    activity.onNavigationDrawerItemSelected(NavigationDrawerFragment.ITEM_SETTINGS);
    if (BuildConfig.DEBUG
        && !(activity.getSupportFragmentManager().findFragmentById(R.id.page_container)
            instanceof SettingsFragment)) {
      throw new AssertionError();
    }
  }
    public SupportRequestManagerHarness() {
      supportFragment = new SupportRequestManagerFragment(lifecycle);
      supportController = Robolectric.buildActivity(FragmentActivity.class).create();

      supportController
          .get()
          .getSupportFragmentManager()
          .beginTransaction()
          .add(supportFragment, TAG)
          .commit();
      supportController.get().getSupportFragmentManager().executePendingTransactions();
    }
Пример #22
0
 @Before
 public void setUp() {
   controller =
       Robolectric.buildActivity(TestListActivity.class)
           .create()
           .postCreate(null)
           .start()
           .resume()
           .visible();
   activity = controller.get();
   shadowOf(activity).clickMenuItem(android.R.id.home);
 }
  @Before
  public void setUp() throws Exception {
    Activity context = Robolectric.buildActivity(Activity.class).create().get();
    relativeLayout = new RelativeLayout(context);
    relativeLayout.setId((int) Utils.generateUniqueId());
    viewGroup = new LinearLayout(context);

    BaseForwardingNativeAd baseForwardingNativeAd = new BaseForwardingNativeAd() {};
    baseForwardingNativeAd.setTitle("test title");
    baseForwardingNativeAd.setText("test text");
    baseForwardingNativeAd.setCallToAction("test call to action");
    baseForwardingNativeAd.setClickDestinationUrl("destinationUrl");

    nativeResponse =
        new NativeResponse(
            context,
            "impressionTrackerUrl",
            "clickTrackerUrl",
            "test ID",
            baseForwardingNativeAd,
            mock(MoPubNative.MoPubNativeListener.class));

    titleView = new TextView(context);
    titleView.setId((int) Utils.generateUniqueId());
    textView = new TextView(context);
    textView.setId((int) Utils.generateUniqueId());
    callToActionView = new Button(context);
    callToActionView.setId((int) Utils.generateUniqueId());
    mainImageView = new ImageView(context);
    mainImageView.setId((int) Utils.generateUniqueId());
    iconImageView = new ImageView(context);
    iconImageView.setId((int) Utils.generateUniqueId());
    badView = new ImageView(context);
    badView.setId((int) Utils.generateUniqueId());

    relativeLayout.addView(titleView);
    relativeLayout.addView(textView);
    relativeLayout.addView(callToActionView);
    relativeLayout.addView(mainImageView);
    relativeLayout.addView(iconImageView);
    relativeLayout.addView(badView);

    viewBinder =
        new ViewBinder.Builder(relativeLayout.getId())
            .titleId(titleView.getId())
            .textId(textView.getId())
            .callToActionId(callToActionView.getId())
            .mainImageId(mainImageView.getId())
            .iconImageId(iconImageView.getId())
            .build();

    subject = new MoPubNativeAdRenderer(viewBinder);
  }
Пример #24
0
  @Test
  public void shouldHaveContextInScopeMapAfterOnCreate() throws Exception {
    final ActivityController<A> aController = Robolectric.buildActivity(A.class);
    final A a = aController.get();

    assertThat(a.getScopedObjectMap().size(), equalTo(0));
    aController.create();

    boolean found = false;
    for (Object o : a.getScopedObjectMap().values()) if (o == a) found = true;

    assertTrue("Couldn't find context in scope map", found);
  }
  @Test
  public void testCantSetPublishThenReadPermissions() throws Exception {
    Activity activity = Robolectric.buildActivity(MainActivity.class).create().get();

    LoginButton loginButton = (LoginButton) activity.findViewById(R.id.login_button);
    loginButton.setPublishPermissions("publish_actions");
    try {
      loginButton.setReadPermissions("user_location");
    } catch (UnsupportedOperationException e) {
      return;
    }
    fail();
  }
Пример #26
0
@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) {}
  }
}
  @Before
  public void setUp() throws Exception {
    server = new MockWebServer();
    server.play();

    Activity activity = Robolectric.buildActivity(Activity.class).get();
    loader =
        new UrlConnectionDownloader(activity) {
          @Override
          protected HttpURLConnection openConnection(Uri path) throws IOException {
            return (HttpURLConnection) server.getUrl(path.toString()).openConnection();
          }
        };
  }
Пример #28
0
  @Test
  public void shouldHaveTwoItemsInScopeMapAfterOnCreate() throws Exception {
    final ActivityController<B> bController = Robolectric.buildActivity(B.class);
    final B b = bController.get();

    assertThat(b.getScopedObjectMap().size(), equalTo(0));
    bController.create();

    boolean found = false;
    for (Object o : b.getScopedObjectMap().values()) if (o == b) found = true;

    assertTrue("Couldn't find context in scope map", found);
    assertTrue(b.getScopedObjectMap().containsKey(Key.get(C.class)));
  }
  @Before
  public void setUp() throws Exception {
    Activity activity = Robolectric.buildActivity(Activity.class).create().get();
    initMocks(activity);

    // Using the default configuration for the base ad adapter (positioner(3,3))
    mFlurryBaseAdAdapter = new FlurryBaseAdAdapter(mMockAdapter);
    mFlurryBaseAdAdapter.initAdFetcher(activity);
    mFlurryBaseAdAdapter.injectMockAdFetcher(mMockNativeAdFetcher);

    // Mock default FlurryNativeAdFetcher behaviour
    doNothing().when(mMockNativeAdFetcher).prefetchAds(anyString());
    // doReturn(mMockFlurryAdNative).when(mMockNativeAdFetcher).popLoadedAd();
  }
 @Before
 public void setup() {
   RoboGuice.setBaseApplicationInjector(
       Robolectric.application,
       Stage.DEVELOPMENT,
       RoboGuice.newDefaultRoboModule(Robolectric.application),
       new ModuleA());
   ActionBarSherlock.registerImplementation(ActionBarSherlockRobolectric.class);
   Intent intent =
       new Intent(Robolectric.application, DummySherlockActivity.class)
           .putExtra("foobar", "goober");
   activity =
       Robolectric.buildActivity(DummySherlockActivity.class).withIntent(intent).create().get();
 }