Java Code Examples for android.support.test.rule.ActivityTestRule

The following are top voted examples for showing how to use android.support.test.rule.ActivityTestRule. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: asaf-project   File: FruitViewRotationTestStateBuilder.java   View source code 7 votes vote down vote up
ActivityTestRule<FruitActivity>  createRule(){

        return new ActivityTestRule<FruitActivity>(FruitActivity.class) {
            @Override
            protected void beforeActivityLaunched() {

                new SystemLogger().i("FruitViewRotationTestStateBuilder", "beforeActivityLaunched()");

                CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext();
                customApp.injectSynchronousObjectGraph();
                //inject our test model
                customApp.injectMockObject(FruitFetcher.class, fruitViewRotationTest.fruitFetcher);
                customApp.registerActivityLifecycleCallbacks(new ProgressBarIdler());

            }

            @Override
            protected void afterActivityFinished() {
                super.afterActivityFinished();

                this.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        };
    }
 
Example 2
Project: orgzly-android   File: MiscTest.java   View source code 6 votes vote down vote up
@Test
public void testReposActivityFragments() {
    ActivityTestRule rule = new ActivityTestRule<>(ReposActivity.class, true, false);

    shelfTestUtils.setupBook("book-one", "Preface\n\n* Note");
    shelfTestUtils.setupRepo("file:/");
    shelfTestUtils.setupRepo("dropbox:/orgzly");
    rule.launchActivity(null);

    // List of repos
    fragmentTest(rule, false, withId(R.id.fragment_repos_flipper));

    // Directory repo
    onListItem(1).perform(click());
    fragmentTest(rule, false, withId(R.id.fragment_repo_directory_container));
    pressBack();

    // Dropbox repo
    onListItem(0).perform(click());
    fragmentTest(rule, false, withId(R.id.fragment_repo_dropbox_container));
}
 
Example 3
Project: orgzly-android   File: MiscTest.java   View source code 6 votes vote down vote up
private void fragmentTest(ActivityTestRule rule, boolean hasSearchMenuItem, Matcher<View> matcher) {
    onView(matcher).check(matches(isDisplayed()));
    toPortrait(rule);
    onView(matcher).check(matches(isDisplayed()));
    toLandscape(rule);
    onView(matcher).check(matches(isDisplayed()));
    toPortrait(rule);
    onView(matcher).check(matches(isDisplayed()));
    toLandscape(rule);
    onView(matcher).check(matches(isDisplayed()));
    toPortrait(rule);

    if (hasSearchMenuItem) {
        onView(withId(R.id.activity_action_search)).check(matches(isDisplayed()));
    } else {
        onView(withId(R.id.activity_action_search)).check(doesNotExist());
    }
}
 
Example 4
Project: asaf-project   File: StateBuilder.java   View source code 6 votes vote down vote up
ActivityTestRule<CounterActivity>  createRule(){

        return new ActivityTestRule<CounterActivity>(CounterActivity.class) {
            @Override
            protected void beforeActivityLaunched() {

                //get hold of the application
                CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext();
                customApp.injectSynchronousObjectGraph();

                //inject our mocks so our UI layer will pick them up
                customApp.injectMockObject(CounterWithLambdas.class, mockCounterWithLambdas);
                customApp.injectMockObject(CounterWithProgress.class, mockCounterWithProgress);
            }

        };
    }
 
Example 5
Project: asaf-project   File: FruitViewTestStateBuilder.java   View source code 6 votes vote down vote up
ActivityTestRule<FruitActivity>  createRule(){

        return new ActivityTestRule<FruitActivity>(FruitActivity.class) {
            @Override
            protected void beforeActivityLaunched() {

                //get hold of the application
                CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext();
                customApp.injectSynchronousObjectGraph();

                //inject our mocks so our UI layer will pick them up
                customApp.injectMockObject(FruitFetcher.class, mockFruitFetcher);
                customApp.registerActivityLifecycleCallbacks(new ProgressBarIdler());
            }

        };
    }
 
Example 6
Project: asaf-project   File: StateBuilder.java   View source code 6 votes vote down vote up
ActivityTestRule<WalletsActivity>  createRule(){

        return new ActivityTestRule<WalletsActivity>(WalletsActivity.class) {
            @Override
            protected void beforeActivityLaunched() {

                //get hold of the application
                CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext();
                customApp.injectSynchronousObjectGraph();

                //inject our mocks so our UI layer will pick them up
                customApp.injectMockObject(Wallet.class, mockWallet);
            }

        };
    }
 
Example 7
Project: asaf-project   File: StateBuilder.java   View source code 6 votes vote down vote up
ActivityTestRule<PlaylistsActivity>  createRule(){

        return new ActivityTestRule<PlaylistsActivity>(PlaylistsActivity.class) {
            @Override
            protected void beforeActivityLaunched() {

                //get hold of the application
                CustomApp customApp = (CustomApp) InstrumentationRegistry.getTargetContext().getApplicationContext();
                customApp.injectSynchronousObjectGraph();

                //inject our mocks so our UI layer will pick them up
                customApp.injectMockObject(PlaylistAdvancedModel.class, mockPlaylistAdvancedModel);
                customApp.injectMockObject(PlaylistSimpleModel.class, mockPlaylistSimpleModel);
            }

        };
    }
 
Example 8
Project: 2016.2-MissaoNascente   File: RegisterAcceptanceTest.java   View source code 6 votes vote down vote up
@Test
public void testRegisterUserPasswordInvalid(){
    new ActivityTestRule<>(RegisterScreenActivity.class);

    onView(withId(R.id.nicknameEditText))
            .perform(typeText("testuser"));
    onView(withId(R.id.passwordEditText))
            .perform(typeText("!*"));
    onView(withId(R.id.passwordConfirmEditText))
            .perform(typeText("senha1234"))
            .perform(closeSoftKeyboard());
    onView(withId(R.id.emailEditText))
            .perform(typeText("[email protected]"))
            .perform(closeSoftKeyboard());
    onView(withId(R.id.registerButton))
            .perform(click());
    onView(withId(R.id.passwordEditText)).check(matches(hasErrorText(activity.getString(R.string.passwordValidation))));
}
 
Example 9
Project: 2016.2-MissaoNascente   File: RegisterAcceptanceTest.java   View source code 6 votes vote down vote up
@Test
public void testRegisterUserConfirmPasswordInvalid(){
    new ActivityTestRule<>(RegisterScreenActivity.class);

    onView(withId(R.id.nicknameEditText))
            .perform(typeText("testuser"));
    onView(withId(R.id.passwordEditText))
            .perform(typeText("senha1234"));
    onView(withId(R.id.passwordConfirmEditText))
            .perform(typeText("!*"))
            .perform(closeSoftKeyboard());
    onView(withId(R.id.emailEditText))
            .perform(typeText("[email protected]"))
            .perform(closeSoftKeyboard());
    onView(withId(R.id.registerButton))
            .perform(click());
    onView(withId(R.id.passwordConfirmEditText)).check(matches(hasErrorText(activity.getString(R.string.passwordConfirmValidation))));
}
 
Example 10
Project: 2016.2-MissaoNascente   File: RegisterAcceptanceTest.java   View source code 6 votes vote down vote up
@Test
public void testRegisterUserEmailInvalid(){
    new ActivityTestRule<>(RegisterScreenActivity.class);

    onView(withId(R.id.nicknameEditText))
            .perform(typeText("testuser"));
    onView(withId(R.id.passwordEditText))
            .perform(typeText("senha1234"));
    onView(withId(R.id.passwordConfirmEditText))
            .perform(typeText("senha1234"))
            .perform(closeSoftKeyboard());
    onView(withId(R.id.emailEditText))
            .perform(typeText("[email protected]"))
            .perform(closeSoftKeyboard());
    onView(withId(R.id.registerButton))
            .perform(click());
    onView(withId(R.id.emailEditText)).check(matches(hasErrorText(activity.getString(R.string.invalidEmail))));
}
 
Example 11
Project: material-components-android   File: ActivityUtils.java   View source code 6 votes vote down vote up
/**
 * Restarts the RecreatedAppCompatActivity and waits for the new activity to be resumed.
 *
 * @return The newly-restarted RecreatedAppCompatActivity
 */
@SuppressWarnings("unchecked") // The type of the recreated activity is guaranteed to be T
public static <T extends RecreatableAppCompatActivity> T recreateActivity(
    ActivityTestRule<? extends RecreatableAppCompatActivity> rule, final T activity)
    throws InterruptedException {
  // Now switch the orientation
  RecreatableAppCompatActivity.resumedLatch = new CountDownLatch(1);
  RecreatableAppCompatActivity.destroyedLatch = new CountDownLatch(1);
  runOnUiThreadRethrow(
      rule,
      new Runnable() {
        @Override
        public void run() {
          activity.recreate();
        }
      });
  assertTrue(RecreatableAppCompatActivity.resumedLatch.await(1, TimeUnit.SECONDS));
  assertTrue(RecreatableAppCompatActivity.destroyedLatch.await(1, TimeUnit.SECONDS));
  T newActivity = (T) RecreatableAppCompatActivity.activity;
  waitForExecution(rule);
  RecreatableAppCompatActivity.clearState();
  return newActivity;
}
 
Example 12
Project: material-activity-chooser   File: ActivityUtils.java   View source code 6 votes vote down vote up
/**
 * Gets an instance of the currently active (displayed) activity.
 * @param activityTestRule test rule
 * @param <T> activity class
 * @return activity instance
 */
public static  <T extends Activity> T getCurrentActivity(@NonNull ActivityTestRule activityTestRule) {
    getInstrumentation().waitForIdleSync();
    final Activity[] activity = new Activity[1];
    try {
        activityTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                java.util.Collection<Activity> activites = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
                activity[0] = Iterables.getOnlyElement(activites);
            }});
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    //noinspection unchecked
    return (T) activity[0];
}
 
Example 13
Project: android-java-snippets-sample   File: SnippetListActivityTests.java   View source code 6 votes vote down vote up
public static void Disconnect(ActivityTestRule<SnippetListActivity> snippetListActivityTestRule) {
    SnippetListActivity snippetListActivity = snippetListActivityTestRule.launchActivity(null);

    openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext());

    // Espresso can't find menu items by id. We'll use the text property.
    onView(withText(R.string.disconnect_menu_item))
            .perform(click());

    intended(allOf(
            hasComponent(hasShortClassName(".SignInActivity")),
            toPackage("com.microsoft.graph.snippets")
    ));

    snippetListActivity.finish();
}
 
Example 14
Project: android-java-snippets-sample   File: SnippetListActivityTests.java   View source code 6 votes vote down vote up
public static List<Integer> getSnippetsIndexes(ActivityTestRule<SnippetListActivity> snippetListActivityRule) {
    SnippetListActivity snippetListActivity = snippetListActivityRule.launchActivity(null);

    ListAdapter listAdapter = getListAdapter(snippetListActivity);
    int numItems = listAdapter.getCount();

    List<Integer> snippetIndexes = new ArrayList<>();

    // Get the index of items in the adapter that
    // are actual snippets and not categories, which don't have a Url
    for (int i = 0; i < numItems; i++) {
        if(((AbstractSnippet)listAdapter.getItem(i)).getUrl() != null) {
            snippetIndexes.add(i);
        }
    }

    snippetListActivity.finish();

    return snippetIndexes;
}
 
Example 15
Project: ommvplib   File: TestHelper.java   View source code 5 votes vote down vote up
public static void rotateOrientation(ActivityTestRule<? extends Activity> testRule) {
    switch (testRule.getActivity().getResources().getConfiguration().orientation) {
        case Configuration.ORIENTATION_LANDSCAPE:
            testRule.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            break;
        default:
            testRule.getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}
 
Example 16
Project: orgzly-android   File: EspressoUtils.java   View source code 5 votes vote down vote up
private static void toOrientation(ActivityTestRule activityRule, int requestedOrientation) {
    activityRule.getActivity().setRequestedOrientation(requestedOrientation);

    /* Not pretty, but it does seem to fix testFragments from randomly failing. */
    try {
        // Thread.sleep(1000);
        Thread.sleep(750);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 17
Project: android-architecture-components   File: EspressoTestUtil.java   View source code 5 votes vote down vote up
/**
 * Disables progress bar animations for the views of the given activity rule
 *
 * @param activityTestRule The activity rule whose views will be checked
 */
public static void disableProgressBarAnimations(
        ActivityTestRule<? extends FragmentActivity> activityTestRule) {
    activityTestRule.getActivity().getSupportFragmentManager()
            .registerFragmentLifecycleCallbacks(
            new FragmentManager.FragmentLifecycleCallbacks() {
                @Override
                public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v,
                        Bundle savedInstanceState) {
                    // traverse all views, if any is a progress bar, replace its animation
                    traverseViews(v);
                }
            }, true);
}
 
Example 18
Project: android-architecture-components   File: EspressoTestUtil.java   View source code 5 votes vote down vote up
/**
 * Disables progress bar animations for the views of the given activity rule
 *
 * @param activityTestRule The activity rule whose views will be checked
 */
public static void disableAnimations(
        ActivityTestRule<? extends FragmentActivity> activityTestRule) {
    activityTestRule.getActivity().getSupportFragmentManager()
            .registerFragmentLifecycleCallbacks(
                    new FragmentManager.FragmentLifecycleCallbacks() {
                        @Override
                        public void onFragmentViewCreated(FragmentManager fm, Fragment f, View v,
                                Bundle savedInstanceState) {
                            // traverse all views, if any is a progress bar, replace its animation
                            traverseViews(v);
                        }
                    }, true);
}
 
Example 19
Project: espresso-utils   File: EspressoUtils.java   View source code 5 votes vote down vote up
private void rotateScreen(ActivityTestRule<?> activityRule) {
    Context context = InstrumentationRegistry.getTargetContext();
    int orientation = context.getResources().getConfiguration().orientation;

    Activity activity = activityRule.getActivity();
    activity.setRequestedOrientation(
            (orientation == Configuration.ORIENTATION_PORTRAIT) ?
                    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
 
Example 20
Project: android-keep-testing   File: TestUtils.java   View source code 5 votes vote down vote up
public static void rotateScreen(ActivityTestRule<? extends Activity> activityRule) {
    Context context = InstrumentationRegistry.getTargetContext();
    int orientation
            = context.getResources().getConfiguration().orientation;

    Activity activity = activityRule.getActivity();
    activity.setRequestedOrientation(
            (orientation == Configuration.ORIENTATION_PORTRAIT) ?
                    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE :
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
 
Example 21
Project: delern   File: WaitView.java   View source code 5 votes vote down vote up
/**
 * Brings activity to foreground, if it is already launched, or launches it.
 *
 * @param rule activity rule for the activity to operate on.
 * @param <T>  activity class.
 */
public static <T extends Activity> void bringToFront(final ActivityTestRule<T> rule) {
    final T runningActivity = rule.getActivity();
    if (runningActivity == null) {
        rule.launchActivity(null);
    } else {
        // TODO(dotdoom): launch using runningActivity.getIntent()? E.g. to preserve username
        //                and save roundtrip to login window.
        final Intent intent = new Intent(runningActivity, runningActivity.getClass());
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        runningActivity.startActivity(intent);
    }
}
 
Example 22
Project: generator-ymca   File: TestUtils.java   View source code 5 votes vote down vote up
public static void rotateOrientation(ActivityTestRule<? extends Activity> activityTestRule) {
    int currentOrientation =
            activityTestRule.getActivity().getResources().getConfiguration().orientation;

    switch (currentOrientation) {
        case Configuration.ORIENTATION_LANDSCAPE:
            rotateToPortrait(activityTestRule);
            break;
        case Configuration.ORIENTATION_PORTRAIT:
            rotateToLandscape(activityTestRule);
            break;
        default:
            rotateToLandscape(activityTestRule);
    }
}
 
Example 23
Project: unity-ads-android   File: LifecycleListenerTest.java   View source code 5 votes vote down vote up
protected Activity waitForActivityStart (final ActivityTestRule rule) {
	final ConditionVariable cv = new ConditionVariable();
	WebViewApp.setCurrentApp(new WebViewApp() {
		private boolean allowEvents = false;

		@Override
		public boolean sendEvent(Enum eventCategory, Enum eventId, Object... params) {
			if ("CREATED".equals(eventId.name())) {
				allowEvents = true;
			}

			if (allowEvents && params[0].equals("com.unity3d.ads.test.unit.LifecycleListenerTestActivity")) {
				DeviceLog.debug(eventId.name() + " " + params[0]);

				EVENTS.add(eventId);
				EVENT_PARAMS.add(params);
				EVENT_COUNT++;
			}

			return true;
		}
	});

	new Thread(new Runnable() {
		@Override
		public void run() {
			rule.launchActivity(new Intent());
			cv.open();
		}
	}).start();

	boolean success = cv.block(30000);
	return rule.getActivity();
}
 
Example 24
Project: material-components-android   File: ActivityUtils.java   View source code 5 votes vote down vote up
public static void waitForExecution(
    final ActivityTestRule<? extends RecreatableAppCompatActivity> rule) {
  // Wait for two cycles. When starting a postponed transition, it will post to
  // the UI thread and then the execution will be added onto the queue after that.
  // The two-cycle wait makes sure fragments have the opportunity to complete both
  // before returning.
  try {
    rule.runOnUiThread(DO_NOTHING);
    rule.runOnUiThread(DO_NOTHING);
  } catch (Throwable throwable) {
    throw new RuntimeException(throwable);
  }
}
 
Example 25
Project: material-components-android   File: ActivityUtils.java   View source code 5 votes vote down vote up
private static void runOnUiThreadRethrow(
    ActivityTestRule<? extends RecreatableAppCompatActivity> rule, Runnable r) {
  if (Looper.getMainLooper() == Looper.myLooper()) {
    r.run();
  } else {
    try {
      rule.runOnUiThread(r);
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }
}
 
Example 26
Project: material-components-android   File: BackLayerLayoutTestBase.java   View source code 5 votes vote down vote up
/**
 * Sets up the necessary members for this test class from a BackLayerLayoutActivity. Call this
 * method from a {@code @Before} method on the subclass.
 */
public void setUp(
    ActivityTestRule<? extends Activity> activityTestRule,
    @IdRes int coordinatorLayoutId,
    @IdRes int backLayerId,
    @IdRes int contentLayerId,
    @IdRes int primaryButtonId,
    @IdRes int secondaryButtonId,
    @IdRes int primaryExtraContentId,
    @IdRes int secondaryExtraContentId)
    throws Exception {
  this.backLayerId = backLayerId;
  this.contentLayerId = contentLayerId;
  activity = activityTestRule.getActivity();
  resources = activity.getResources();

  coordinatorLayout = activity.findViewById(coordinatorLayoutId);
  backLayer = activity.findViewById(backLayerId);
  contentLayer = activity.findViewById(contentLayerId);
  primaryExtraContent = activity.findViewById(primaryExtraContentId);
  secondaryExtraContent = activity.findViewById(secondaryExtraContentId);

  this.primaryButtonId = primaryButtonId;
  this.secondaryButtonId = secondaryButtonId;
  this.primaryExtraContentId = primaryExtraContentId;
  this.secondaryExtraContentId = secondaryExtraContentId;

  CoordinatorLayout.LayoutParams layoutParams =
      (CoordinatorLayout.LayoutParams) backLayer.getLayoutParams();
  int absoluteGravity =
      Gravity.getAbsoluteGravity(layoutParams.gravity, ViewCompat.getLayoutDirection(backLayer));
  isBackLayerAtEndSide = absoluteGravity == Gravity.RIGHT || absoluteGravity == Gravity.BOTTOM;
  isHorizontal = absoluteGravity == Gravity.RIGHT || absoluteGravity == Gravity.LEFT;

  if (backLayer.isExpanded()) {
    onView(withId(backLayerId)).perform(collapse());
  }
}
 
Example 27
Project: DebugRank   File: RepositoryBehaviorTest.java   View source code 5 votes vote down vote up
@Override
protected void init(ActivityTestRule activityTestRule)
{
    super.init(activityTestRule);

    userRepo = (MemoryUserRepository) app.getUserRepository();
    dataRepo = (MemoryDataRepository) app.getDataRepository();
}
 
Example 28
Project: Movies   File: PopularMoviesActivityTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();
    backend = (ConfigurableBackend) ((TestPopularMoviesComponent) movieApplication.getPopularMoviesComponent()).backend();

    rule = new ActivityTestRule<>(PopularMoviesActivity.class);

    apiMoviePoster = createApiMoviePoster(MOVIE_ID, POSTER_PATH);
    movieDetails = createMovieDetails(MOVIE_ID, MOVIE_TITLE, MOVIE_DESCRIPTION, POSTER_PATH, RELEASE_DATE);
}
 
Example 29
Project: Movies   File: MovieDetailsActivityTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MovieApplication movieApplication = (MovieApplication) InstrumentationRegistry.getTargetContext().getApplicationContext();

    backend = (ConfigurableBackend) ((TestMovieDetailsComponent) movieApplication.getMovieDetailsComponent()).backend();
    apiMovieDetails = createApiMovieDetails(MOVIE_ID, MOVIE_TITLE, MOVIE_DESCRIPTION, POSTER_PATH, RELEASE_DATE);
    rule = new ActivityTestRule<>(MovieDetailsActivity.class);
}
 
Example 30
Project: The_Elucidated   File: Database_FunctionsTest.java   View source code 5 votes vote down vote up
@Before
public void startMainActivityFromHomeScreen() {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

    // Start from the home screen
    mDevice.pressHome();

    // Wait for launcher
    final String launcherPackage = mDevice.getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
            LAUNCH_TIMEOUT);

    // Launch the app
    appContext = InstrumentationRegistry.getContext();
    final Intent intent = appContext.getPackageManager()
            .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
    // Clear out any previous instances
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    appContext.startActivity(intent);

    // Wait for the app to appear
    mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
            LAUNCH_TIMEOUT);

    ActivityTestRule<Activity> mActivityRule = new ActivityTestRule<>(
            Activity.class);

    database_functions = Database_Functions.getInstance(appContext, mActivityRule.getActivity());
}
 
Example 31
Project: The_Elucidated   File: Database_FunctionsTest.java   View source code 5 votes vote down vote up
@Test
public void getInstance() throws Exception {
    ActivityTestRule<Activity> mActivityRule = new ActivityTestRule<>(
            Activity.class);

    database_functions = Database_Functions.getInstance(appContext, mActivityRule.getActivity());
}
 
Example 32
Project: tagscout   File: TestUtils.java   View source code 5 votes vote down vote up
public static void rotateOrientation(ActivityTestRule<? extends Activity> activityTestRule) {
    int currentOrientation =
            activityTestRule.getActivity().getResources().getConfiguration().orientation;

    switch (currentOrientation) {
        case Configuration.ORIENTATION_LANDSCAPE:
            rotateToPortrait(activityTestRule);
            break;
        case Configuration.ORIENTATION_PORTRAIT:
            rotateToLandscape(activityTestRule);
            break;
        default:
            rotateToLandscape(activityTestRule);
    }
}
 
Example 33
Project: MicroPinner   File: MainDialogThemeTest.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@ColorInt
private static int getAccentColor(@NonNull ActivityTestRule<MainDialog> activityTestRule, boolean light) {
    Configuration configuration = new Configuration();
    configuration.uiMode = light ? Configuration.UI_MODE_NIGHT_NO : Configuration.UI_MODE_NIGHT_YES;

    return ContextCompat.getColor(activityTestRule.getActivity().createConfigurationContext(configuration), R.color.accent);
}
 
Example 34
Project: MicroPinner   File: MainDialogThemeTest.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@ColorInt
private static int getBackgroundColor(@NonNull ActivityTestRule<MainDialog> activityTestRule, boolean light) {
    Configuration configuration = new Configuration();
    configuration.uiMode = light ? Configuration.UI_MODE_NIGHT_NO : Configuration.UI_MODE_NIGHT_YES;

    return ContextCompat.getColor(activityTestRule.getActivity().createConfigurationContext(configuration), R.color.background);
}
 
Example 35
Project: Android-DatePicker-Sample   File: DatePickerTest.java   View source code 5 votes vote down vote up
private void launchDatePickerInFragmentActivity(List<ActivityTheme> activityThemeList, final Class<DatePickerInFragmentActivity> clazz){
    for(DatePickerMode datePickerMode : DatePickerMode.values()){
        for(int i = 0; i < 2; i++){
            boolean isCalendarViewShown = i == 0;
            for(int j = 0; j < 2; j++){
                boolean isSpinnersShown = j == 0;
                for(ActivityTheme activityTheme : activityThemeList){
                    if(datePickerMode == DatePickerMode.Calendar && activityTheme == ActivityTheme.Theme_Black){
                        continue;
                    }
                    final Intent intent = MainActivity.createIntent(activityTestRule.getActivity(),
                        clazz,
                        datePickerMode.layout,
                        isCalendarViewShown,
                        isSpinnersShown,
                        activityTheme.theme);
                    ActivityTestRule<DatePickerInFragmentActivity> rule = new ActivityTestRule<>(clazz, false);
                    String fileName = String.format("%s_%s_%s_%s_%s_%s_%s.png",
                        clazz.getSimpleName(),
                        datePickerMode.name(),
                        "isCalendarViewShown",
                        isCalendarViewShown,
                        "isSpinnersShown",
                        isSpinnersShown,
                        activityTheme.name());
                    Log.d(clazz.getSimpleName(), fileName);
                    rule.launchActivity(intent);
                    takeScreenshot(rule.getActivity(), fileName);
                }
            }
        }
    }
}
 
Example 36
Project: Android-DatePicker-Sample   File: DatePickerTest.java   View source code 5 votes vote down vote up
private void launchDatePickerInAppCompatActivity(List<ActivityTheme> activityThemeList, final Class<DatePickerInAppCompatActivity> clazz){
    for(DatePickerMode datePickerMode : DatePickerMode.values()){
        for(int i = 0; i < 2; i++){
            boolean isCalendarViewShown = i == 0;
            for(int j = 0; j < 2; j++){
                boolean isSpinnersShown = j == 0;
                for(ActivityTheme activityTheme : activityThemeList){
                    if(datePickerMode == DatePickerMode.Calendar && activityTheme == ActivityTheme.Theme_Black){
                        continue;
                    }
                    final Intent intent = MainActivity.createIntent(activityTestRule.getActivity(),
                        clazz,
                        datePickerMode.layout,
                        isCalendarViewShown,
                        isSpinnersShown,
                        activityTheme.theme);
                    ActivityTestRule<DatePickerInAppCompatActivity> rule = new ActivityTestRule<>(clazz, false);
                    String fileName = String.format("%s_%s_%s_%s_%s_%s_%s.png",
                        clazz.getSimpleName(),
                        datePickerMode.name(),
                        "isCalendarViewShown",
                        isCalendarViewShown,
                        "isSpinnersShown",
                        isSpinnersShown,
                        activityTheme.name());
                    Log.d(clazz.getSimpleName(), fileName);
                    rule.launchActivity(intent);
                    takeScreenshot(rule.getActivity(), fileName);
                }
            }
        }
    }
}
 
Example 37
Project: kickmaterial   File: DaggerRules.java   View source code 5 votes vote down vote up
public static <ACTIVITY extends Activity> ActivityTestRule<ACTIVITY> getActivityRule(final AppComponentProvider mainComponentProv,
                                                                                     Class<ACTIVITY> clazz) {
    final Handler mainHandler = new Handler(Looper.getMainLooper());
    return new DaggerActivityTestRule<>(clazz, (application, activity) -> {
        final KickMaterialApp app = (KickMaterialApp) application;
        final AppComponent appComponent = mainComponentProv.getComponent(app);
        final GlobalComponent globalComponent = DaggerGlobalComponent.builder()
                .globalModule(new GlobalModule(app, appComponent.getBus(), appComponent.getAccessTokenProvider()))
                .build();
        mainHandler.post(() -> app.setComponents(globalComponent, appComponent));
    });
}
 
Example 38
Project: Bill-Calculator   File: Tester.java   View source code 5 votes vote down vote up
public void changeOrientation(ActivityTestRule<DrawerActivity> testRule) {
    int current = testRule.getActivity().getRequestedOrientation();
    int change;
    if (current == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        change = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
    } else if (current == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {
        change = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        testRule.getActivity().setRequestedOrientation(change);
        change = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
    } else {
        change = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }
    testRule.getActivity().setRequestedOrientation(change);
}
 
Example 39
Project: iosched   File: OrientationHelper.java   View source code 5 votes vote down vote up
public static void rotateOrientation(ActivityTestRule<? extends Activity> activityTestRule) {
    int currentOrientation =
            activityTestRule.getActivity().getResources().getConfiguration().orientation;

    switch (currentOrientation) {
        case Configuration.ORIENTATION_LANDSCAPE:
            rotateToPortrait(activityTestRule);
            break;
        case Configuration.ORIENTATION_PORTRAIT:
            rotateToLandscape(activityTestRule);
            break;
        default:
            rotateToLandscape(activityTestRule);
    }
}
 
Example 40
Project: DebugOverlay-Android   File: SystemLayerInstrumentedTest.java   View source code 4 votes vote down vote up
@Override
ActivityTestRule getActivityRule() {
    return activityRule;
}