Java源码示例:org.robolectric.util.ActivityController

示例1
@Test
public void LoadReceipt()
{
    Intent intent = new Intent();
    final Bundle bundle = new Bundle();
    bundle.putString("receipt", "receipt");
    intent.putExtras(bundle);

    ActivityController activityController =  Robolectric.buildActivity(
        ReceiptViewActivity.class).withIntent(intent).create();
    activityController.start();
    activityController.resume();

    Activity activity = (Activity)activityController.get();
    WebView receiptView = (WebView)activity.findViewById(R.id.imageView);

    ShadowWebView.LoadDataWithBaseURL loadedData = shadowOf(receiptView).getLastLoadDataWithBaseURL();
    assertEquals("", loadedData.baseUrl);
    assertEquals("text/html", loadedData.mimeType);
    assertEquals("utf-8", loadedData.encoding);
    assertNull(loadedData.historyUrl);
    assertTrue(loadedData.data.contains("src=\"file://receipt\""));
}
 
示例2
private void applyState(ActivityState state,
                        ActivityController controller) {
    switch (state) {
        case STARTED:
            controller.start();
            break;
        case RESUMED:
            controller.resume();
            break;
        case PAUSED:
            controller.pause();
            break;
        case STOPPED:
            controller.stop();
            break;
        case DESTROYED:
            controller.destroy();
            break;
        case CREATED:
        default:
            controller.create();
            break;
    }
}
 
示例3
@Test
public void onLoginLoad_withEmptyScopes_shouldReturnErrorResultIntent() {
    Intent intent = new Intent();
    intent.putExtra(LoginActivity.EXTRA_SESSION_CONFIGURATION, new SessionConfiguration.Builder().setClientId(CLIENT_ID).build());

    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class)
            .withIntent(intent)
            .create();

    ShadowActivity shadowActivity = shadowOf(controller.get());

    assertThat(shadowActivity.getResultCode()).isEqualTo(Activity.RESULT_CANCELED);
    assertThat(shadowActivity.getResultIntent()).isNotNull();
    assertThat(getErrorFromIntent(shadowActivity.getResultIntent()))
            .isEqualTo(AuthenticationError.INVALID_SCOPE);
    assertThat(shadowActivity.isFinishing()).isTrue();
}
 
示例4
@Test
public void onLoginLoad_withNullResponseType_shouldReturnErrorResultIntent() {
    Intent intent = new Intent();
    intent.putExtra(LoginActivity.EXTRA_SESSION_CONFIGURATION, loginConfiguration);
    intent.putExtra(LoginActivity.EXTRA_RESPONSE_TYPE, (ResponseType) null);

    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class)
            .withIntent(intent)
            .create();

    ShadowActivity shadowActivity = shadowOf(controller.get());

    assertThat(shadowActivity.getResultCode()).isEqualTo(Activity.RESULT_CANCELED);
    assertThat(shadowActivity.getResultIntent()).isNotNull();
    assertThat(getErrorFromIntent(shadowActivity.getResultIntent()))
            .isEqualTo(AuthenticationError.INVALID_RESPONSE_TYPE);
    assertThat(shadowActivity.isFinishing()).isTrue();
}
 
示例5
@Test
public void onLoginLoad_withSsoEnabled_andNotSupported_shouldReturnErrorResultIntent() {
    Intent intent = LoginActivity.newIntent(Robolectric.setupActivity(Activity.class), productPriority,
            loginConfiguration, ResponseType.TOKEN, false, true, true);

    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class).withIntent(intent);
    loginActivity = controller.get();
    loginActivity.ssoDeeplinkFactory = ssoDeeplinkFactory;
    ShadowActivity shadowActivity = shadowOf(loginActivity);
    when(ssoDeeplink.isSupported(SsoDeeplink.FlowVersion.REDIRECT_TO_SDK)).thenReturn(false);

    controller.create();

    assertThat(shadowActivity.getResultCode()).isEqualTo(Activity.RESULT_CANCELED);
    assertThat(shadowActivity.getResultIntent()).isNotNull();
    assertThat(getErrorFromIntent(shadowActivity.getResultIntent()))
            .isEqualTo(AuthenticationError.INVALID_REDIRECT_URI);
    assertThat(shadowActivity.isFinishing()).isTrue();
}
 
示例6
@Test
public void onLoginLoad_withResponseTypeToken_andNotForceWebview_andPrivilegedScopes_andRedirectToPlayStoreDisabled_shouldLoadChrometab() {
    loginConfiguration = new SessionConfiguration.Builder()
            .setClientId(CLIENT_ID)
            .setRedirectUri(REDIRECT_URI)
            .setScopes(MIXED_SCOPES)
            .build();
    Intent intent = LoginActivity.newIntent(Robolectric.setupActivity(Activity.class), loginConfiguration,
            ResponseType.TOKEN, false);

    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class).withIntent(intent);
    loginActivity = controller.get();
    loginActivity.customTabsHelper = customTabsHelper;
    controller.create();

    String expectedUrl = AuthUtils.buildUrl(REDIRECT_URI, ResponseType.TOKEN, loginConfiguration);
    verify(customTabsHelper).openCustomTab(any(LoginActivity.class), any(CustomTabsIntent.class),
            eq(Uri.parse(expectedUrl)), any(CustomTabsHelper.BrowserFallback.class));
}
 
示例7
@Test
public void onLoadLoginView_withNoRedirectUrl_shouldReturnError() {
    SessionConfiguration config = new SessionConfiguration.Builder().setClientId("clientId").build();
    Intent intent = new Intent();
    intent.putExtra(LoginActivity.EXTRA_SESSION_CONFIGURATION, config);
    final ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class)
            .withIntent(intent);
    final ShadowActivity shadowActivity = Shadows.shadowOf(controller.get());

    controller.create();

    assertThat(shadowActivity.isFinishing()).isTrue();
    assertThat(shadowActivity.getResultCode()).isEqualTo(Activity.RESULT_CANCELED);
    assertThat(shadowActivity.getResultIntent()).isNotNull();
    assertThat(shadowActivity.getResultIntent().getStringExtra(LoginManager.EXTRA_ERROR)).isNotEmpty();
}
 
示例8
@Test
public void testArgKeyGeneration() {
    String s = UUID.randomUUID().toString();
    int i = new Random(42).nextInt();

    Bundle bundle = new Bundle();
    bundle.putString("ARG_A_STRING", s);
    bundle.putInt("ARG_AN_INT", i);

    ActivityController<SimpleFragmentActivity> initialController = Robolectric.buildActivity(SimpleFragmentActivity.class).create();
    SimpleFragmentActivity simpleActivity = initialController.start().restart().visible().get();
    KeyGenFragment fragment = KeyGenFragment.newInstance();
    fragment.setArguments(bundle);
    simpleActivity.replaceFragment(fragment);

    assertEquals(s, fragment.aString);
    assertEquals(i, fragment.anInt);
}
 
示例9
@Test
public void testMultiAnnotationActivity() throws Exception {
    Random random = new Random();

    Intent intent = new Intent(RuntimeEnvironment.application, MultiAnnotationActivity.class);
    int extraInt = random.nextInt();
    intent.putExtra(MultiAnnotationActivity.EXTRA_INT, extraInt);

    ActivityController<MultiAnnotationActivity> saveController = Robolectric.buildActivity(MultiAnnotationActivity.class).withIntent(intent).create();
    MultiAnnotationActivity activity = saveController.start().restart().visible().get();

    assertEquals(extraInt, activity.i);

    int activityInt = random.nextInt();
    activity.i = activityInt;


    Bundle saveState = new Bundle();
    saveController.saveInstanceState(saveState);

    ActivityController<MultiAnnotationActivity> restoreController = Robolectric.buildActivity(MultiAnnotationActivity.class).withIntent(intent)
            .create(saveState);
    activity = restoreController.start().restart().visible().get();

    assertEquals(activityInt, activity.i);
}
 
示例10
@Test
public void shouldFinishLoginActivityWhenCompleted() {

    Activity context = Robolectric
            .buildActivity(Activity.class)
            .create()
            .get();

    AuthenticationRequest request = new AuthenticationRequest.Builder("test", AuthenticationResponse.Type.TOKEN, "test://test").build();
    AuthenticationResponse response = new AuthenticationResponse.Builder()
            .setType(AuthenticationResponse.Type.TOKEN)
            .setAccessToken("test_token")
            .setExpiresIn(3600)
            .build();

    Bundle bundle = new Bundle();
    bundle.putParcelable(LoginActivity.REQUEST_KEY, request);

    Intent intent = new Intent(context, LoginActivity.class);
    intent.putExtra(LoginActivity.EXTRA_AUTH_REQUEST, bundle);

    ActivityController<LoginActivity> loginActivityActivityController = buildActivity(LoginActivity.class)
            .withIntent(intent);

    final LoginActivity loginActivity = loginActivityActivityController.get();

    final ShadowActivity shadowLoginActivity = shadowOf(loginActivity);
    shadowLoginActivity.setCallingActivity(context.getComponentName());

    loginActivityActivityController.create();

    assertFalse(loginActivity.isFinishing());

    loginActivity.onClientComplete(response);

    assertTrue(loginActivity.isFinishing());
    assertEquals(Activity.RESULT_OK, shadowLoginActivity.getResultCode());
    assertEquals(response, shadowLoginActivity.getResultIntent().getBundleExtra(LoginActivity.EXTRA_AUTH_RESPONSE).get(LoginActivity.RESPONSE_KEY));
}
 
示例11
@Test
public void addOneGiftCard()
{
    ActivityController activityController = Robolectric.buildActivity(MainActivity.class).create();

    Activity mainActivity = (Activity)activityController.get();
    activityController.start();
    activityController.resume();

    TextView helpText = (TextView)mainActivity.findViewById(R.id.helpText);
    ListView list = (ListView)mainActivity.findViewById(R.id.list);

    assertEquals(0, list.getCount());

    DBHelper db = new DBHelper(mainActivity);
    db.insertGiftCard("store", "cardId", "value", "receipt");

    assertEquals(View.VISIBLE, helpText.getVisibility());
    assertEquals(View.GONE, list.getVisibility());

    activityController.pause();
    activityController.resume();

    assertEquals(View.GONE, helpText.getVisibility());
    assertEquals(View.VISIBLE, list.getVisibility());

    assertEquals(1, list.getAdapter().getCount());
    Cursor cursor = (Cursor)list.getAdapter().getItem(0);
    assertNotNull(cursor);
}
 
示例12
@Nullable
public ActivityController getActivityController() {
    if (androidUnitTest.getActivityController() != null) {
        return androidUnitTest.getActivityController();
    }
    return null;
}
 
示例13
public Activity createAndInitActivity(Class activityClass, @Nullable RActivity activityAnnotation) {
    ActivityController activityController = ActivityController.of(Robolectric.getShadowsAdapter(), activityClass);
    androidUnitTest.setActivityController(activityController);
    if (activityAnnotation != null) {
        ActivityState activityState = activityAnnotation.state();
        setActivityState(activityController, activityState);
    }
    Activity activity = (Activity) activityController.get();
    return Mockito.spy(activity);
}
 
示例14
public ControllerActivity setActivityState(ActivityController activityController, ActivityState activityState) {
    ActivityState init = ActivityState.CREATED;

    while (init != null && init.isLowerOrEquals(activityState)) {
        System.out.println(init);
        applyState(init, activityController);
        init = init.next();
    }

    return this;
}
 
示例15
@Test
public void testExecute() throws Exception {
    // Given
    TestObject testObject = new TestObject();
    Context context = new Application();
    manager.activityField = testObject.getClass().getDeclaredField("activity");
    // When
    manager.execute(testObject, context);
    //Then
    assertThat(testObject.activity).isNotNull();
    assertThat(testObject.activity.created).isTrue();
    verify(androidUnitTest).setActivityController(any(ActivityController.class));
}
 
示例16
@Test
public void testExecuteState() throws Exception {
    // Given
    TestObjectState testObject = new TestObjectState();
    Context context = new Application();
    manager.activityField = testObject.getClass().getDeclaredField("activity");
    // When
    manager.execute(testObject, context);
    //Then
    assertThat(testObject.activity).isNotNull();
    assertThat(testObject.activity.created).isTrue();
    assertThat(testObject.activity.started).isTrue();
    assertThat(testObject.activity.resumed).isTrue();
    verify(androidUnitTest).setActivityController(any(ActivityController.class));
}
 
示例17
@Test
public void onLoginLoad_withEmptySessionConfiguration_shouldReturnErrorResultIntent() {
    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class);
    controller.create();

    ShadowActivity shadowActivity = shadowOf(controller.get());

    assertThat(shadowActivity.getResultCode()).isEqualTo(Activity.RESULT_CANCELED);
    assertThat(shadowActivity.getResultIntent()).isNotNull();
    assertThat(getErrorFromIntent(shadowActivity.getResultIntent()))
            .isEqualTo(AuthenticationError.INVALID_PARAMETERS);
    assertThat(shadowActivity.isFinishing()).isTrue();
}
 
示例18
@Test
public void onLoginLoad_withSsoEnabled_andSupported_shouldExecuteSsoDeeplink() {
    Intent intent = LoginActivity.newIntent(Robolectric.setupActivity(Activity.class), productPriority,
            loginConfiguration, ResponseType.TOKEN, false, true, true);

    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class).withIntent(intent);
    loginActivity = controller.get();
    loginActivity.ssoDeeplinkFactory = ssoDeeplinkFactory;

    when(ssoDeeplink.isSupported(SsoDeeplink.FlowVersion.REDIRECT_TO_SDK)).thenReturn(true);

    controller.create();

    verify(ssoDeeplink).execute(SsoDeeplink.FlowVersion.REDIRECT_TO_SDK);
}
 
示例19
@Test
public void onLoginLoad_withResponseTypeCode_andNotForceWebview_shouldLoadChrometab() {
    Intent intent = LoginActivity.newIntent(Robolectric.setupActivity(Activity.class), loginConfiguration,
            ResponseType.CODE, false);

    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class).withIntent(intent);
    loginActivity = controller.get();
    loginActivity.customTabsHelper = customTabsHelper;
    controller.create();

    String expectedUrl = AuthUtils.buildUrl(REDIRECT_URI, ResponseType.CODE, loginConfiguration);
    verify(customTabsHelper).openCustomTab(any(LoginActivity.class), any(CustomTabsIntent.class),
            eq(Uri.parse(expectedUrl)), any(CustomTabsHelper.BrowserFallback.class));
}
 
示例20
@Test
public void onLoginLoad_withResponseTypeToken_andNotForceWebview_andGeneralScopes_shouldLoadChrometab() {
    Intent intent = LoginActivity.newIntent(Robolectric.setupActivity(Activity.class), loginConfiguration,
            ResponseType.TOKEN, false);

    ActivityController<LoginActivity> controller = Robolectric.buildActivity(LoginActivity.class).withIntent(intent);
    loginActivity = controller.get();
    loginActivity.customTabsHelper = customTabsHelper;
    controller.create();

    String expectedUrl = AuthUtils.buildUrl(REDIRECT_URI, ResponseType.TOKEN, loginConfiguration);
    verify(customTabsHelper).openCustomTab(any(LoginActivity.class), any(CustomTabsIntent.class),
            eq(Uri.parse(expectedUrl)), any(CustomTabsHelper.BrowserFallback.class));
}
 
示例21
@Test (expected = IllegalStateException.class)
public void verifyNullBundleException() {
    ActivityController<SimpleFragmentActivity> initialController = Robolectric.buildActivity(SimpleFragmentActivity.class).create();
    SimpleFragmentActivity simpleActivity = initialController.start().restart().visible().get();
    SimpleFragment simpleFragment = SimpleFragment.newInstance();
    simpleActivity.replaceFragment(simpleFragment);
}
 
示例22
@Test (expected = IllegalStateException.class)
public void verifyArgumentBindingException() {
    Bundle bundle = new Bundle();
    ActivityController<SimpleFragmentActivity> initialController = Robolectric.buildActivity(SimpleFragmentActivity.class).create();
    SimpleFragmentActivity simpleActivity = initialController.start().restart().visible().get();
    SimpleFragment simpleFragment = SimpleFragment.newInstance();
    simpleFragment.setArguments(bundle);
    simpleActivity.replaceFragment(simpleFragment);
}
 
示例23
@Test
public void verifyNotRequiredArgumentBinding() {
    ActivityController<SimpleFragmentActivity> initialController = Robolectric.buildActivity(SimpleFragmentActivity.class).create();
    SimpleFragmentActivity simpleActivity = initialController.start().restart().visible().get();
    NotRequiredArgFragment fragment = new NotRequiredArgFragment();
    simpleActivity.replaceFragment(fragment);

    assertEquals(1, fragment.i);
    assertEquals("NOT_REQUIRED", fragment.s);
}
 
示例24
@Test
public void editTrackActivityStoresChanges() throws Exception {
    openMethod.invoke(dataSource);
    Track t = new Track("Testing", "Run my tests");
    t.setEnabled(true);
    dataSource.storeTrack(t);
    closeMethod.invoke(dataSource);
    assertThat(t, equalTo(t));

    Intent i = new Intent(RuntimeEnvironment.application.getApplicationContext(), tickmate.getClass());
    i.putExtra("track_id", t.getId());
    ActivityController<TrackPreferenceActivity> r_eta = Robolectric.buildActivity(TrackPreferenceActivity.class)
            .withIntent(i)
            .create(new Bundle())
            .start()
            .resume();

    TrackPreferenceActivity eta = r_eta.get();
    TrackPreferenceFragment tpf = (TrackPreferenceFragment) eta.getFragmentManager().findFragmentById(android.R.id.content);
    EditTextPreference description = (EditTextPreference) tpf.findPreference("description");
    assertThat(description.getText().toString(), is("Run my tests"));
    description.setText("Krishna Hare");

    r_eta.pause();
    r_eta.stop();

    Track t_also = dataSource.getTrack(t.getId());

    assertThat(t, equalTo(t_also));
    assertThat(t_also.getName(), is(t.getName()));
    assertThat(t_also.getIcon(), is(t.getIcon()));
    assertThat(t_also.getDescription(), is("Krishna Hare"));
    assertThat(t_also.isEnabled(), is(t.isEnabled()));
}
 
示例25
@Test
public void testInstantiation() {
    String expected = "Robolectric is running with Gradle";

    ActivityController<Activity> activity = Robolectric.buildActivity(Activity.class);
    TextView textView = new TextView(activity.get().getApplicationContext());
    textView.setText(expected);

    assertEquals(expected, textView.getText());
}
 
示例26
@Nullable
public ActivityController getActivityController() {
    return activityController;
}
 
示例27
public void setActivityController(@Nullable ActivityController activityController) {
    this.activityController = activityController;
}
 
示例28
@Test
public void testInheritance() throws Exception {
    Random random = new Random(42);

    Bundle args = new Bundle();
    int parentArg = random.nextInt();
    int childArg = random.nextInt();
    args.putInt(ChildFragment.CHILD_ARG, childArg);
    args.putInt(ParentFragment.PARENT_ARG, parentArg);

    Intent intent = new Intent(RuntimeEnvironment.application, GrandchildActivity.class);
    int parentExtra = random.nextInt();
    int childExtra = random.nextInt();
    intent.putExtra(ParentActivity.PARENT_EXTRA, parentExtra);
    intent.putExtra(ChildActivity.CHILD_EXTRA, childExtra);
    intent.putExtra(ChildActivity.FRAGMENT_ARGS, args);

    ActivityController<GrandchildActivity> initialController = Robolectric.buildActivity(GrandchildActivity.class).withIntent(intent).create();
    GrandchildActivity originalActivity = initialController.start().restart().visible().get();

    assertEquals(childExtra, originalActivity.childExtra);
    assertEquals(parentExtra, originalActivity.parentExtra);

    assertEquals(childArg, originalActivity.fragment.childArg);
    assertEquals(parentArg, originalActivity.fragment.parentArg);

    originalActivity.paInt = random.nextInt();
    originalActivity.caInt = random.nextInt();

    originalActivity.fragment.pfInt = random.nextInt();
    originalActivity.fragment.cfInt = random.nextInt();

    Bundle saveState = new Bundle();
    initialController.saveInstanceState(saveState);


    Bundle copyArgs = new Bundle();
    copyArgs.putInt(ChildFragment.CHILD_ARG, random.nextInt() - childArg);
    copyArgs.putInt(ParentFragment.PARENT_ARG, random.nextInt() - parentArg);

    Intent copyIntent = new Intent(RuntimeEnvironment.application, GrandchildActivity.class);
    copyIntent.putExtra(ParentActivity.PARENT_EXTRA, random.nextInt() - parentExtra);
    copyIntent.putExtra(ChildActivity.CHILD_EXTRA, random.nextInt() - childExtra);
    copyIntent.putExtra(ChildActivity.FRAGMENT_ARGS, copyArgs);

    ActivityController<GrandchildActivity> secondaryController = Robolectric.buildActivity(GrandchildActivity.class).withIntent(copyIntent).create(saveState);
    GrandchildActivity copyActivity = secondaryController.start().restart().visible().get();

    assertEquals(originalActivity.caInt, copyActivity.caInt);
    assertEquals(originalActivity.paInt, copyActivity.paInt);

    assertEquals(originalActivity.fragment.cfInt, copyActivity.fragment.cfInt);
    assertEquals(originalActivity.fragment.pfInt, copyActivity.fragment.pfInt);
}
 
示例29
private <T extends Activity> T createActivity(Class<T> activityClass) {
	ActivityController<T> controller = Robolectric.buildActivity(activityClass);
	controller.create();
	return controller.get();
}
 
示例30
private <T extends Activity> T createActivity(Class<T> activityClass) {
	ActivityController<T> controller = Robolectric.buildActivity(activityClass);
	controller.create();
	return controller.get();
}