下面列出了android.app.ActivityManager.RunningTaskInfo#org.robolectric.Robolectric 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void shouldFailWithDialogWhenPermissionsAreNotGranted() {
when(handler.parseRequestResult(PERMISSION_REQUEST_CODE, PROVIDER_PERMISSIONS, PERMISSIONS_GRANTED)).thenReturn(Arrays.asList("some", "values"));
Activity activity = Robolectric.buildActivity(Activity.class).create().resume().get();
provider.start(activity, callback, PERMISSION_REQUEST_CODE, AUTHENTICATION_REQUEST_CODE);
provider.onRequestPermissionsResult(activity, PERMISSION_REQUEST_CODE, PROVIDER_PERMISSIONS, PERMISSIONS_GRANTED);
ArgumentCaptor<Dialog> dialogCaptor = ArgumentCaptor.forClass(Dialog.class);
verify(callback).onFailure(dialogCaptor.capture());
final Dialog dialog = dialogCaptor.getValue();
assertThat(dialog, is(instanceOf(Dialog.class)));
assertThat(dialog, is(notNullValue()));
dialog.show(); //Load the layout
TextView messageTV = dialog.findViewById(android.R.id.message);
assertThat(messageTV.getText().toString(), containsString("Some permissions required by this provider were not granted. You can try to authenticate again or go to " +
"the application's permission screen in the phone settings and grant them. The missing permissions are:\n" + "[some, values]"));
}
@Test
public void testInterstitialANClickThroughActionSDKBrowser() {
interstitialAdView.setClickThroughAction(ANClickThroughAction.OPEN_SDK_BROWSER);
server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.noFillCSM_RTBInterstitial()));
executeInterstitialRequest();
waitUntilExecuted();
waitForTasks();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
waitForTasks();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
assertTrue(adClicked);
assertFalse(adClickedWithUrl);
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
TestApplication.applicationGraph.inject(this);
reset(itemManager);
reset(keyDelegate);
controller = Robolectric.buildActivity(ThreadPreviewActivity.class,
new Intent().putExtra(ThreadPreviewActivity.EXTRA_ITEM,
new TestHnItem(2L) {
@Override
public String getBy() {
return "username";
}
}));
activity = controller
.create().start().resume().visible().get();
}
@Test
public void testClearExperimentTest() throws InterruptedException, JSONException {
siberiStorage.insert("test_001_change_button_color", 2, createMetaData());
final ExperimentContent result = new ExperimentContent("test");
Siberi.clearExperimentContent();
Thread.sleep(500); //wait for clear content task to end
Siberi.ExperimentRunner runner = new Siberi.ExperimentRunner() {
@Override
public void run(ExperimentContent content) {
result.setTestName(content.testName);
result.setVariant(content.variant);
result.setMetaData(content.metaData);
}
};
Siberi.runTest("test_001_change_button_color", runner);
Thread.sleep(500); //wait for run test action to be finished
Robolectric.flushForegroundThreadScheduler();
Thread.sleep(500); //wait for applying test result
assertThat(result.getTestName(),is("test_001_change_button_color"));
assertFalse(result.containsVariant());
}
@Test
public void testOnStartShouldSignOutIfConfigurationHasChanged() throws CanceledException, JSONException {
// Create new configuration to change the hash
Context context = RuntimeEnvironment.application.getApplicationContext();
new OAuthClientConfiguration(
context,
context.getSharedPreferences(OAuthClientConfiguration.PREFS_NAME, MODE_PRIVATE),
ConfigurationStreams.getOtherConfiguration()
);
doNothing().when(mCancelIntent).send();
OktaManagementActivity activity = Robolectric.buildActivity(
OktaManagementActivity.class
).newIntent(createStartIntent()).create().start().get();
assertThat(activity.isFinishing()).isTrue();
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
TestApplication.applicationGraph.inject(this);
reset(itemManager);
controller = Robolectric.buildActivity(WebActivity.class);
activity = controller.get();
PreferenceManager.getDefaultSharedPreferences(activity)
.edit()
.putBoolean(activity.getString(R.string.pref_lazy_load), false)
.apply();
shadowOf((ConnectivityManager) RuntimeEnvironment.application
.getSystemService(Context.CONNECTIVITY_SERVICE))
.setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null,
ConnectivityManager.TYPE_WIFI, 0, true, NetworkInfo.State.CONNECTED));
}
@Before
public void setup() throws Exception {
application = (TestMapzenApplication) Robolectric.application;
application.inject(this);
TestHelper.initBaseActivity();
TestMap testMap = (TestMap) mapController.getMap();
viewController = Mockito.mock(ViewController.class);
testMap.setViewport(viewController);
task = new DrawPathTask(application);
box = Mockito.mock(BoundingBox.class);
stub(viewController.getBBox()).toReturn(box);
outsideBefore1 = new Location("f");
outsideBefore1.setLatitude(1);
outsideBefore2 = new Location("f");
outsideBefore2.setLatitude(2);
inside1 = new Location("f");
inside1.setLatitude(3);
inside2 = new Location("f");
inside2.setLatitude(4);
outSideAfter1 = new Location("f");
outSideAfter1.setLatitude(5);
outSideAfter2 = new Location("f");
outSideAfter2.setLatitude(6);
}
@Test
public void testLazyBannerAdLoadedFailureAndLoadAgainSuccess() {
server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.invalidBanner()));
bannerAdView.enableLazyLoad();
assertFalse(bannerAdView.getChildAt(0) instanceof WebView);
executeBannerRequest();
assertLazyLoadCallbackInProgress();
bannerAdView.loadLazyAd();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
assertLazyLoadCallbackFailure();
adLoaded = false;
adFailed = false;
adLazyLoaded = false;
restartServer();
server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.banner()));
executeBannerRequest();
assertLazyLoadCallbackInProgress();
assertFalse(bannerAdView.getChildAt(0) instanceof WebView);
bannerAdView.loadLazyAd();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
assertLazyLoadCallbackSuccess();
}
@Test
public void merging() {
TestDb db0 = new TestDb(Robolectric.application);
TestDb db1 = new TestDb(Robolectric.application);
db0.insertRow(0, 0l, 0f, 0d, (short) 0, true, new byte[]{0, 0}, "0");
db0.insertRow(1, 1l, 1f, 1d, (short) 1, true, new byte[]{1, 1}, "1");
db1.insertRow(2, 2l, 2f, 2d, (short) 2, true, new byte[]{2, 2}, "2");
db1.insertRow(3, 3l, 3f, 3d, (short) 3, true, new byte[]{3, 3}, "3");
IterableCursor<Pojo> cursor = new IterableMergeCursor<Pojo>(
new PojoCursor(db0.query()), new PojoCursor(db1.query()));
Pojo[] samples = new Pojo[]{
new Pojo(0, 0l, 0f, 0d, (short) 0, true, new byte[]{0, 0}, "0"),
new Pojo(1, 1l, 1f, 1d, (short) 1, true, new byte[]{1, 1}, "1"),
new Pojo(2, 2l, 2f, 2d, (short) 2, true, new byte[]{2, 2}, "2"),
new Pojo(3, 3l, 3f, 3d, (short) 3, true, new byte[]{3, 3}, "3")
};
iterationHelper(cursor, samples);
}
private void triggerConfigurationChange(BraintreeUnitTestHttpClient httpClient) {
Bundle bundle = new Bundle();
mActivityController.saveInstanceState(bundle)
.pause()
.stop()
.destroy();
mActivityController = Robolectric.buildActivity(AddCardUnitTestActivity.class);
mActivity = (AddCardUnitTestActivity) mActivityController.get();
mShadowActivity = shadowOf(mActivity);
mActivity.httpClient = httpClient;
mActivityController.setup(bundle);
mActivity.braintreeFragment.onAttach(mActivity);
mActivity.braintreeFragment.onResume();
setupViews();
}
@Test
public void testForwardsRedirectToManagementActivity() {
Uri redirectUri = Uri.parse("https://www.example.com/oauth2redirect");
Intent redirectIntent = new Intent();
redirectIntent.setData(redirectUri);
ActivityController redirectController =
Robolectric.buildActivity(RedirectUriReceiverActivity.class, redirectIntent)
.create();
RedirectUriReceiverActivity redirectActivity =
(RedirectUriReceiverActivity) redirectController.get();
Intent nextIntent = shadowOf(redirectActivity).getNextStartedActivity();
assertThat(nextIntent).hasData(redirectUri);
assertThat(redirectActivity).isFinishing();
}
@Test
public void guardMultipleViews() {
CountClickListener listener = new CountClickListener() {
@Override
public void onClick(View v) {
super.onClick(v);
assertEquals(1, getClickedCount());
}
};
View view1 = new View(Robolectric.application);
view1.setOnClickListener(listener);
View view2 = new View(Robolectric.application);
view2.setOnClickListener(listener);
View view3 = new View(Robolectric.application);
view3.setOnClickListener(listener);
ClickGuard.guard(view1, view2, view3);
clickViews(view1, view2, view3);
}
@Test
public void testResetViewStatus() {
ActivityController<NavigationSourceUtility.TestActivity> controller = Robolectric.buildActivity(NavigationSourceUtility.TestActivity.class).create().start().resume();
NavigationSourceUtility.TestActivity testActivity = controller.get();
View view = new View(testActivity);
view.setTranslationX(1);
view.setTranslationY(1);
view.setScaleX(2.0f);
view.setScaleY(2.0f);
view.setRotation(1.0f);
view.setRotationX(1.0f);
view.setRotationY(1.0f);
view.setAlpha(0.5f);
view.startAnimation(new AlphaAnimation(0.0f, 1.0f));
AnimatorUtility.resetViewStatus(view);
assertEquals(0.0f, view.getTranslationX(), 0.0f);
assertEquals(0.0f, view.getTranslationY(), 0.0f);
assertEquals(1.0f, view.getScaleX(), 0.0f);
assertEquals(1.0f, view.getScaleY(), 0.0f);
assertEquals(0.0f, view.getRotation(), 0.0f);
assertEquals(0.0f, view.getRotationX(), 0.0f);
assertEquals(0.0f, view.getRotationY(), 0.0f);
assertEquals(1.0f, view.getAlpha(), 0.0f);
assertNull(view.getAnimation());
}
@Test
public void testTimeOut() throws Exception {
PrebidMobile.setPrebidServerHost(Host.APPNEXUS);
PrebidMobile.setTimeoutMillis(30);
PrebidMobile.setPrebidServerAccountId("b7adad2c-e042-4126-8ca1-b3caac7d3e5c");
PrebidMobile.setShareGeoLocation(true);
PrebidMobile.setApplicationContext(activity.getApplicationContext());
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(0, 250));
RequestParams requestParams = new RequestParams("e2edc23f-0b3b-4203-81b5-7cc97132f418", AdType.BANNER, sizes);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);
@SuppressWarnings("unchecked")
ArrayList<PrebidServerAdapter.ServerConnector> connectors = (ArrayList<PrebidServerAdapter.ServerConnector>) FieldUtils.readDeclaredField(adapter, "serverConnectors", true);
PrebidServerAdapter.ServerConnector connector = connectors.get(0);
PrebidServerAdapter.ServerConnector.TimeoutCountDownTimer timeoutCountDownTimer = (PrebidServerAdapter.ServerConnector.TimeoutCountDownTimer) FieldUtils.readDeclaredField(connector, "timeoutCountDownTimer", true);
shadowOf(timeoutCountDownTimer).invokeFinish();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
verify(mockListener).onDemandFailed(ResultCode.TIMEOUT, uuid);
}
@Test
public void testOmidNativeRendererJSEvents() {
server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.anNativeRenderer()));
adRequest.loadAd();
Lock.pause(1000);
waitForTasks();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
waitForTasks();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.getForegroundThreadScheduler().runOneTask();
assertAdLoaded(true);
assertVerificationScriptResourceNativeRenderer();
assertANOMIDAdSessionPresent();
attachNativeAdToViewAndRegisterTracking();
assertOMIDSessionStartRenderer();
NativeAdSDK.unRegisterTracking(dummyNativeView);
Lock.pause(1000);
waitForTasks();
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
assertOMIDSessionFinish();
}
/**
* Testing show info method
*/
@Test
public void showInfoMessageTest() {
final BaseFragmentActivity activity =
Robolectric.buildActivity(getActivityClass(), getIntent()).setup().get();
TextView messageView = new TextView(activity);
messageView.setId(R.id.flying_message);
messageView.setVisibility(View.GONE);
activity.addContentView(messageView, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
assertThat(messageView).hasText("");
final String message = "test";
assertShowInfoMessage(activity, message, new Runnable() {
@Override
public void run() {
assumeTrue(activity.showInfoMessage(message));
}
});
}
@Test
public void shouldVerifyInstance_stateTitle() {
when(environmentService.findAll()).thenReturn(Observable.empty());
ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
activity = controller
.create()
.start()
.resume()
.visible()
.get();
ButterKnife.bind(this, activity);
assertEquals("wrong title", labelAppName, activity.getSupportActionBar().getTitle());
String CUSTOM_TITLE = "myNewTitle";
activity.getSupportActionBar().setTitle(CUSTOM_TITLE);
activity = controller
.stop()
.resume()
.visible()
.get();
assertEquals("wrong title", CUSTOM_TITLE, activity.getSupportActionBar().getTitle());
}
@Test
public void testUpdateTimeoutMillis() {
PrebidMobile.setPrebidServerHost(Host.APPNEXUS);
assertEquals(2000, PrebidMobile.getTimeoutMillis());
assertFalse(PrebidMobile.timeoutMillisUpdated);
PrebidMobile.setPrebidServerAccountId("b7adad2c-e042-4126-8ca1-b3caac7d3e5c");
PrebidMobile.setShareGeoLocation(true);
PrebidMobile.setApplicationContext(activity.getApplicationContext());
DemandAdapter.DemandAdapterListener mockListener = mock(DemandAdapter.DemandAdapterListener.class);
PrebidServerAdapter adapter = new PrebidServerAdapter();
HashSet<AdSize> sizes = new HashSet<>();
sizes.add(new AdSize(300, 250));
RequestParams requestParams = new RequestParams("e2edc23f-0b3b-4203-81b5-7cc97132f418", AdType.BANNER, sizes);
String uuid = UUID.randomUUID().toString();
adapter.requestDemand(requestParams, mockListener, uuid);
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
verify(mockListener).onDemandFailed(ResultCode.NO_BIDS, uuid);
assertTrue("Actual Prebid Mobile timeout is " + PrebidMobile.getTimeoutMillis(), PrebidMobile.getTimeoutMillis() <= 2000 && PrebidMobile.getTimeoutMillis() > 700);
assertTrue(PrebidMobile.timeoutMillisUpdated);
}
@Test
public void testSetupInFragmentLifecycleMethods_Fragment_Added_In_Activity_OnCreate() {
ActivityController<TestAppCompatActivity> controller = Robolectric.buildActivity(TestAppCompatActivity.class).create();
TestAppCompatActivity activity = controller.get();
TestNormalFragment_Add_In_Activity_OnCreate testFragment = new TestNormalFragment_Add_In_Activity_OnCreate();
activity.getSupportFragmentManager().beginTransaction().add(activity.mFrameLayout.getId(), testFragment).commitNowAllowingStateLoss();
controller.start();
controller.resume();
controller.pause();
controller.stop();
controller.destroy();
assertEquals(6, testFragment.mMethodInvokedCount);
}
@Test
public void givenVariantInAttrs_whenCreated_thenHasVariant() {
AttributeSet attrs = Robolectric.buildAttributeSet()
.addAttribute(R.attr.ma_list_item_variant, "two_line_text_icon")
.build();
ListItemView view = new ListItemView(RuntimeEnvironment.application, attrs);
assertThat(view)
.hasVariant(ListItemView.VARIANT_TWO_LINE_TEXT_ICON)
.hasSecondaryTextView()
.hasIconView();
}
private Activity setupActivity() {
when(environmentService.findAll()).thenReturn(Observable.empty());
activity = Robolectric.setupActivity(MainActivity.class);
ButterKnife.bind(this, activity);
return spy(activity);
}
@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);
}
@Test public void shouldStartIntentAfterSuccessfulLaunchPurchaseForSubscription() throws Exception {
shouldStartSetup_SuccessCase();
Bundle response = new Bundle();
response.putParcelable(RESPONSE_BUY_INTENT, PendingIntent.getActivity(Robolectric.application, 0, new Intent(), 0));
when(service.getBuyIntent(API_VERSION, Robolectric.application.getPackageName(), "sku", "subs", "")).thenReturn(response);
Activity activity = mock(Activity.class);
helper.launchPurchaseFlow(activity, "sku", SUBS, TEST_REQUEST_CODE, purchaseFinishedListener, "");
verify(activity).startIntentSenderForResult(any(IntentSender.class), eq(TEST_REQUEST_CODE), any(Intent.class), eq(0), eq(0), eq(0));
}
@Before
public void setUp() {
TestApplication.applicationGraph.inject(this);
reset(itemManager);
ShadowSearchRecentSuggestions.recentQueries.clear();
controller = Robolectric.buildActivity(SearchActivity.class);
activity = controller.get();
}
@Test
public void shouldVerifyInstance_stateFab() {
when(environmentService.findAll()).thenReturn(Observable.empty());
ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
activity = controller
.create()
.start()
.resume()
.visible()
.get();
ButterKnife.bind(this, activity);
activity.floatingActionButtonMain.setVisibility(View.VISIBLE);
assertTrue("invalid state", activity.floatingActionButtonMain.isShown());
activity = controller
.stop()
.resume()
.visible()
.get();
assertTrue("invalid state", activity.floatingActionButtonMain.isShown());
activity.floatingActionButtonMain.setVisibility(View.INVISIBLE);
assertFalse("invalid state", activity.floatingActionButtonMain.isShown());
activity = controller
.stop()
.resume()
.visible()
.get();
assertFalse("invalid state", activity.floatingActionButtonMain.isShown());
}
@Test
public void setFieldHint_setsHintWhenParentViewIsATextInputLayout() {
mView = (CardEditText) Robolectric.setupActivity(TestActivity.class)
.findViewById(R.id.bt_card_form_card_number);
mView.setFieldHint(R.string.bt_form_hint_cvv);
assertEquals("CVV", ((TextInputLayout) mView.getParent().getParent()).getHint());
assertEquals("CVV", mView.getHint());
}
private void initMARWithConvenience() {
BannerAdView bannerAdView = new BannerAdView(activity);
bannerAdView.setPlacementID("0");
bannerAdView.setAdListener(this);
bannerAdView.setAdSize(320, 50);
bannerAdView.setAutoRefreshInterval(-1);
InterstitialAdView interstitialAdView = new InterstitialAdView(activity);
interstitialAdView.setPlacementID("0");
interstitialAdView.setAdListener(this);
new ANMultiAdRequest(activity, 0, 1234, this, true, bannerAdView, interstitialAdView);
waitForTasks();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
waitForTasks();
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
// ShadowLooper shadowLooper = shadowOf(getMainLooper());
// if (!shadowLooper.isIdle()) {
// shadowLooper.idle();
// }
// RuntimeEnvironment.getMasterScheduler().advanceToNextPostedRunnable();
}
@Test
public void getTextInputLayoutParent_returnsTextInputLayout() {
mView = (CardEditText) Robolectric.setupActivity(TestActivity.class)
.findViewById(R.id.bt_card_form_card_number);
assertNotNull(mView.getTextInputLayoutParent());
}
@Test
public void testDrawWindowBackground() {
ActivityController<TestActivity> controller = Robolectric.buildActivity(TestActivity.class).create().resume();
TestActivity activity = controller.get();
SceneDelegate sceneDelegate = NavigationSceneUtility.setupWithActivity(activity, TestScene.class).fixSceneWindowBackgroundEnabled(true).build();
assertNotNull(sceneDelegate.getNavigationScene().requireView().getBackground());
sceneDelegate.abandon();
sceneDelegate = NavigationSceneUtility.setupWithActivity(activity, TestScene.class).drawWindowBackground(false).build();
assertNull(sceneDelegate.getNavigationScene().requireView().getBackground());
}
@Test(expected = NullPointerException.class)
public void testNPE2() {
ActivityController<TestActivity> controller = Robolectric.buildActivity(TestActivity.class).create().start().resume();
TestActivity testActivity = controller.get();
SceneLifecycleManager<NavigationScene> sceneLifecycleManager = new SceneLifecycleManager<>();
sceneLifecycleManager.onActivityCreated(testActivity, testActivity.mFrameLayout,
null, null,
false, null);
}