androidx.test.core.app.ActivityScenario Java Examples

The following examples show how to use androidx.test.core.app.ActivityScenario. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UiControllerImplIntegrationTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void injectKeyEvent() throws InterruptedException {
  try (ActivityScenario<SendActivity> activityScenario =
      ActivityScenario.launch(SendActivity.class)) {
    activityScenario.onActivity(
        activity -> {
          try {
            KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
            KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
            injectEventWorked.set(uiController.injectKeyEvent(events[0]));
            latch.countDown();
          } catch (InjectEventSecurityException e) {
            injectEventThrewSecurityException.set(true);
          }
        });

    assertFalse("injectEvent threw a SecurityException", injectEventThrewSecurityException.get());
    assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
    assertTrue(injectEventWorked.get());
  }
}
 
Example #2
Source File: EventInjectorTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void injectStaleKeyEvent() throws Exception {
  ActivityScenario<SendActivity> scenario = ActivityScenario.launch(SendActivity.class);

  scenario.onActivity(
      sendActivity -> {
        View view = sendActivity.findViewById(R.id.send_data_edit_text);
        assertTrue(view.requestFocus());
        latch.countDown();
      });

  assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
  assertFalse("SecurityException exception was thrown.", injectEventThrewSecurityException.get());

  KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
  KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
  KeyEvent event = KeyEvent.changeTimeRepeat(events[0], 1, 0);

  // Stale event does not fail for API < 13.
  if (Build.VERSION.SDK_INT < 13) {
    assertTrue(injector.injectKeyEvent(event));
  } else {
    assertFalse(injector.injectKeyEvent(event));
  }
}
 
Example #3
Source File: EventInjectorTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void injectKeyEventUpWithNoDown() throws Exception {
  ActivityScenario<SendActivity> scenario = ActivityScenario.launch(SendActivity.class);

  scenario.onActivity(
      sendActivity -> {
        View view = sendActivity.findViewById(R.id.send_data_edit_text);
        assertTrue(view.requestFocus());
        latch.countDown();
      });

  assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
  KeyCharacterMap keyCharacterMap = UiControllerImpl.getKeyCharacterMap();
  KeyEvent[] events = keyCharacterMap.getEvents("a".toCharArray());
  assertTrue(injector.injectKeyEvent(events[1]));
}
 
Example #4
Source File: SwipeOpenItemTouchHelperTest.java    From SwipeOpenItemTouchHelper with Apache License 2.0 6 votes vote down vote up
@Test public void closePositionsTest() {
  try (ActivityScenario<SwipeOpenItemTouchHelperTestActivity> scenario = ActivityScenario.launch(
      SwipeOpenItemTouchHelperTestActivity.class)) {

    scenario.onActivity(activity -> activity.helper.setCloseOnAction(false));

    // open positions 1 and 2
    onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(1, swipeRight()));
    onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(2, swipeLeft()));

    scenario.onActivity(activity -> {
      activity.helper.closeOpenPosition(1);
      activity.helper.closeOpenPosition(2);
    });

    // both positions should be closed
    onView(withText("Test 1")).check(matches(checkZeroTranslation()));
    onView(withText("Test 2")).check(matches(checkZeroTranslation()));
  }
}
 
Example #5
Source File: SwipeOpenItemTouchHelperTest.java    From SwipeOpenItemTouchHelper with Apache License 2.0 6 votes vote down vote up
@Test
public void stateSavingTest() {
  try (ActivityScenario<SwipeOpenItemTouchHelperTestActivity> scenario = ActivityScenario.launch(
      SwipeOpenItemTouchHelperTestActivity.class)) {

    scenario.onActivity(activity -> activity.helper.setCloseOnAction(false));

    // open positions 1 and 2
    onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(1, swipeRight()));
    onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(2, swipeLeft()));

    // recreate the activity
    scenario.recreate();

    // both positions should still be open
    onView(withText("Test 1")).check(matches(checkTranslationX(true)));
    onView(withText("Test 2")).check(matches(checkTranslationX(false)));
  }
}
 
Example #6
Source File: SwipeOpenItemTouchHelperTest.java    From SwipeOpenItemTouchHelper with Apache License 2.0 6 votes vote down vote up
@Test public void swipeCloseOnActionTest() {

    try (ActivityScenario<SwipeOpenItemTouchHelperTestActivity> ignored =
             ActivityScenario.launch(SwipeOpenItemTouchHelperTestActivity.class)) {

      // swipe open position 1
      onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(1, swipeRight()));
      onView(withText("Test 1")).check(matches(checkTranslationX(true)));

      // swipe open position 3
      onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(3, swipeLeft()));

      // position 1 should have closed, and position 3 should be open
      onView(withText("Test 3")).check(matches(checkTranslationX(false)));
      onView(withText("Test 1")).check(matches(checkZeroTranslation()));
    }
  }
 
Example #7
Source File: WayTodayUITest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void wtViewVisibilityWithItag0_shouldReflectTrackingState() {
    Application application = ApplicationProvider.getApplicationContext();
    SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(application);
    p.edit().putInt("freq", 1).apply();
    p.edit().putString("tid", "xxxx").apply();
    p.edit().putBoolean("wt", true).apply();
    p.edit().putBoolean("wtfirst", false).apply();

    try (ActivityScenario<MainActivity> ignored = ActivityScenario.launch(MainActivity.class)) {
        ArgumentCaptor<LocationsTracker.TrackingState> state =
                ArgumentCaptor.forClass(LocationsTracker.TrackingState.class);

        verify(mockTrackingStateListener, timeout(1000).atLeastOnce())
                .onStateChange(state.capture());
        assertThat(LocationsTracker.isUpdating, is(true));
    }
}
 
Example #8
Source File: AdvancedSynchronizationTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  ActivityScenario<SyncActivity> activityScenario = ActivityScenario.launch(SyncActivity.class);
  activityScenario.onActivity(
      activity -> {
        HelloWorldServer realServer = activity.getHelloWorldServer();
        // Here, we use CountingIdlingResource - a common convenience class - to track the idle
        // state of
        // the server. You could also do this yourself, by implementing the IdlingResource
        // interface.
        countingResource = new CountingIdlingResource("HelloWorldServerCalls");

        activity.setHelloWorldServer(new DecoratedHelloWorldServer(realServer, countingResource));
        assertTrue(registerIdlingResources(countingResource));
      });
}
 
Example #9
Source File: AccessibilityChecksTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  ActivityScenario.launch(LargeViewActivity.class);

  // ViewAction to set the height, width to be too small, which will cause an a11y exception
  onView(withId(R.id.large_view)).perform(new ViewAction() {
      @Override
      public String getDescription() {
        return "Set height, width to 0";
      }

      @Override
      public Matcher<View> getConstraints() {
        return isAssignableFrom(View.class);
      }

      @Override
      public void perform(UiController uiController, View view) {
        // set size to be tiny to cause an accessibility error
        view.setLayoutParams(new LayoutParams(1, 1));
      }
    });
}
 
Example #10
Source File: AccessibilityChecksIntegrationTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  ActivityScenario.launch(LargeViewActivity.class);
  // ViewAction to set the height, width to be too small, which will cause an a11y exception
  onView(withId(R.id.large_view))
      .perform(
          new ViewAction() {
            @Override
            public String getDescription() {
              return "Set view size to 1px by 1px";
            }

            @Override
            public Matcher<View> getConstraints() {
              return isAssignableFrom(View.class);
            }

            @Override
            public void perform(UiController uiController, View view) {
              view.setLayoutParams(new LayoutParams(1, 1));
            }
          });
}
 
Example #11
Source File: WayTodayStartStopTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void activity_shouldStartWayToday1h() {
    try (ActivityScenario<MainActivity> ignored = ActivityScenario.launch(MainActivity.class)) {
        Application application = ApplicationProvider.getApplicationContext();
        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(application);

        assertThat(LocationsTracker.isUpdating, is(false));

        ViewInteraction vi = onView(withId(R.id.btn_waytoday));
        vi.perform(click());
        onView(withText(R.string.freq_hour_1))
                .perform(click());
        ArgumentCaptor<LocationsTracker.TrackingState> state =
                ArgumentCaptor.forClass(LocationsTracker.TrackingState.class);

        verify(mockTrackingStateListener, timeout(5000).atLeast(1)).onStateChange(state.capture());
        List<LocationsTracker.TrackingState> states =
                state.getAllValues();
        assertThat(states.size(), greaterThan(0));
        assertThat(states.get(0).isUpdating, is(true));
        assertThat(LocationsTracker.isUpdating, is(true));
        assertThat(p.getInt("freq", -1), equalTo(60 * 60 * 1000));
        assertThat(p.getBoolean("wt", false), is(true));

    }
}
 
Example #12
Source File: WayTodayStartStopTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void activity_shouldStartWayToday5min() {
    try (ActivityScenario<MainActivity> ignored = ActivityScenario.launch(MainActivity.class)) {
        Application application = ApplicationProvider.getApplicationContext();
        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(application);

        assertThat(LocationsTracker.isUpdating, is(false));

        ViewInteraction vi = onView(withId(R.id.btn_waytoday));
        vi.perform(click());
        onView(withText(R.string.freq_min_5))
                .perform(click());
        ArgumentCaptor<LocationsTracker.TrackingState> state =
                ArgumentCaptor.forClass(LocationsTracker.TrackingState.class);

        verify(mockTrackingStateListener, timeout(5000).atLeast(1)).onStateChange(state.capture());
        List<LocationsTracker.TrackingState> states =
                state.getAllValues();
        assertThat(states.size(), greaterThan(0));
        assertThat(states.get(0).isUpdating, is(true));
        assertThat(LocationsTracker.isUpdating, is(true));
        assertThat(p.getInt("freq", -1), equalTo(5 * 60 * 1000));
        assertThat(p.getBoolean("wt", false), is(true));
    }
}
 
Example #13
Source File: WayTodayStartStopTest.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void activity_shouldStartWayTodayContiniously() {
    try (ActivityScenario<MainActivity> ignored = ActivityScenario.launch(MainActivity.class)) {
        Application application = ApplicationProvider.getApplicationContext();
        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(application);

        assertThat(LocationsTracker.isUpdating, is(false));

        ViewInteraction vi = onView(withId(R.id.btn_waytoday));
        vi.perform(click());
        onView(withText(R.string.freq_continuously))
                .perform(click());
        ArgumentCaptor<LocationsTracker.TrackingState> state =
                ArgumentCaptor.forClass(LocationsTracker.TrackingState.class);

        verify(mockTrackingStateListener, timeout(5000).atLeast(1)).onStateChange(state.capture());
        List<LocationsTracker.TrackingState> states =
                state.getAllValues();
        assertThat(states.size(), greaterThan(0));
        assertThat(states.get(0).isUpdating, is(true));
        assertThat(LocationsTracker.isUpdating, is(true));
        assertThat(p.getInt("freq", -1), equalTo(1));
    }
}
 
Example #14
Source File: AccessibilityChecksIntegrationTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  ActivityScenario.launch(LargeViewActivity.class);
  // ViewAction to set the height, width to be too small, which will cause an a11y exception
  onView(withId(R.id.large_view))
      .perform(
          new ViewAction() {
            @Override
            public String getDescription() {
              return "Set view size to 1px by 1px";
            }

            @Override
            public Matcher<View> getConstraints() {
              return isAssignableFrom(View.class);
            }

            @Override
            public void perform(UiController uiController, View view) {
              view.setLayoutParams(new LayoutParams(1, 1));
            }
          });
}
 
Example #15
Source File: DpcLoginActivityTest.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
@Test
public void onDoButtonClick_shouldFinishWithCorrectIntent() {
  ActivityScenario.launch(DpcLoginActivity.class).onActivity(activity -> {
    activity.findViewById(R.id.do_selection_button).performClick();

    assertThat(shadowOf(activity).getResultCode()).isEqualTo(RESULT_OK);
    assertThat(shadowOf(activity).getResultIntent().getIntExtra(EXTRA_PROVISIONING_MODE, -1))
        .isEqualTo(PROVISIONING_MODE_FULLY_MANAGED_DEVICE);
  });
}
 
Example #16
Source File: SwipeOpenItemTouchHelperTest.java    From SwipeOpenItemTouchHelper with Apache License 2.0 5 votes vote down vote up
@Test public void scrollCloseOnActionTest() {
  try (ActivityScenario<SwipeOpenItemTouchHelperTestActivity> ignored = ActivityScenario.launch(
      SwipeOpenItemTouchHelperTestActivity.class)) {

    // swipe open position 2
    onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(2, swipeRight()));
    onView(withText("Test 2")).check(matches(checkTranslationX(true)));

    // scroll on position 3
    onView(withId(R.id.test_recycler)).perform(actionOnItemAtPosition(3, scroll()));

    // position 2 should now be closed
    onView(withText("Test 2")).check(matches(checkZeroTranslation()));
  }
}
 
Example #17
Source File: SwipeOpenItemTouchHelperTest.java    From SwipeOpenItemTouchHelper with Apache License 2.0 5 votes vote down vote up
@Test public void openPositionTest() {
  try (ActivityScenario<SwipeOpenItemTouchHelperTestActivity> scenario =
           ActivityScenario.launch(SwipeOpenItemTouchHelperTestActivity.class)) {
    scenario.onActivity(activity -> {
      activity.helper.setCloseOnAction(true);
      activity.helper.openPositionStart(1);
    });

    onView(withText("Test 1")).check(matches(checkTranslationX(true)));
    scenario.onActivity(activity -> activity.helper.openPositionEnd(2));

    onView(withText("Test 2")).check(matches(checkTranslationX(false)));
    onView(withText("Test 1")).check(matches(checkZeroTranslation()));
  }
}
 
Example #18
Source File: AccessibilityChecksTest.java    From testing-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void accessibilityChecks() {
    AccessibilityChecks.enable();
    try (ActivityScenario scenario = ActivityScenario.launch(MainActivity.class)) {
        onView(withId(R.id.openBrowserButton)).perform(click());
    }
}
 
Example #19
Source File: ChangeTextBehaviorTest.java    From testing-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Use {@link ActivityScenario to launch and get access to the activity.
 * {@link ActivityScenario#onActivity(ActivityScenario.ActivityAction)} provides a thread-safe
 * mechanism to access the activity.
 */
@Before
public void registerIdlingResource() {
    ActivityScenario activityScenario = ActivityScenario.launch(MainActivity.class);
    activityScenario.onActivity(new ActivityScenario.ActivityAction<MainActivity>() {
        @Override
        public void perform(MainActivity activity) {
            mIdlingResource = activity.getIdlingResource();
            // To prove that the test fails, omit this call:
            IdlingRegistry.getInstance().register(mIdlingResource);
        }
    });
}
 
Example #20
Source File: KeyEventActionIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void pressKeyWithKeyCode() {
  ActivityScenario.launch(MainActivity.class);
  onData(allOf(instanceOf(Map.class), hasValue("SendActivity"))).perform(click());
  onView(withId(R.id.enter_data_edit_text)).perform(click());
  onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_X));
  onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_Y));
  onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_Z));
  onView(withId(R.id.enter_data_edit_text)).perform(ViewActions.pressKey(KeyEvent.KEYCODE_ENTER));
  onView(allOf(withId(R.id.enter_data_response_text), withText("xyz")))
      .check(matches(isDisplayed()));
}
 
Example #21
Source File: KeyEventActionIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void clickBackOnNonRootActionNoLatte() {
  ActivityScenario.launch(MainActivity.class);
  onData(allOf(instanceOf(Map.class), hasValue("LargeViewActivity"))).perform(click());
  onView(isRoot()).perform(ViewActions.pressBack());

  // Make sure we are back.
  onData(allOf(instanceOf(Map.class), hasValue("LargeViewActivity")))
      .check(matches(isDisplayed()));
}
 
Example #22
Source File: KeyEventActionIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void clickBackOnNonRootActivityLatte() {
  ActivityScenario.launch(MainActivity.class);
  onData(allOf(instanceOf(Map.class), hasValue("LargeViewActivity"))).perform(click());
  pressBack();

  // Make sure we are back.
  onData(allOf(instanceOf(Map.class), hasValue("LargeViewActivity")))
      .check(matches(isDisplayed()));
}
 
Example #23
Source File: KeyEventActionIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Test only passes if run in isolation. Unless Gradle supports a single instrumentation per test
 * this test is ignored"
 */
@Suppress
@Test
public void clickBackOnRootAction() {
  ActivityScenario.launch(MainActivity.class);
  expectedException.expect(NoActivityResumedException.class);
  pressBack();
}
 
Example #24
Source File: UiControllerImplIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void injectMotionEventSequence() throws InterruptedException {
  try (ActivityScenario<SendActivity> scenario = ActivityScenario.launch(SendActivity.class)) {
    getInstrumentation().waitForIdleSync();
    final float[][] steps = CoordinatesUtil.getCoordinatesToDrag();

    getInstrumentation()
        .runOnMainSync(
            new Runnable() {
              @Override
              public void run() {
                long downTime = SystemClock.uptimeMillis();
                List<MotionEvent> events = new ArrayList<>();
                try {
                  MotionEvent down =
                      MotionEvents.obtainDownEvent(steps[0], new float[] {16f, 16f});
                  events.add(down);
                  for (int i = 1; i < events.size() - 1; i++) {
                    events.add(
                        MotionEvents.obtainMovement(
                            downTime, SystemClock.uptimeMillis(), steps[i]));
                  }
                  events.add(MotionEvents.obtainUpEvent(down, steps[steps.length - 1]));

                  injectEventWorked.set(uiController.injectMotionEventSequence(events));
                  latch.countDown();
                } catch (InjectEventSecurityException e) {
                  injectEventThrewSecurityException.set(true);
                }
              }
            });

    assertFalse(
        "SecurityException exception was thrown.", injectEventThrewSecurityException.get());
    assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
    assertTrue(injectEventWorked.get());
  }
}
 
Example #25
Source File: UiControllerImplIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void injectMotionEvent() throws InterruptedException {
  try (ActivityScenario<SendActivity> activityScenario =
      ActivityScenario.launch(SendActivity.class)) {
    final int[] coords = CoordinatesUtil.getCoordinatesInMiddleOfSendButton(activityScenario);

    getInstrumentation()
        .runOnMainSync(
            new Runnable() {
              @Override
              public void run() {
                long downTime = SystemClock.uptimeMillis();
                try {
                  MotionEvent event =
                      MotionEvent.obtain(
                          downTime,
                          SystemClock.uptimeMillis(),
                          MotionEvent.ACTION_DOWN,
                          coords[0],
                          coords[1],
                          0);

                  injectEventWorked.set(uiController.injectMotionEvent(event));
                  event.recycle();
                  latch.countDown();
                } catch (InjectEventSecurityException e) {
                  injectEventThrewSecurityException.set(true);
                }
              }
            });

    assertFalse(
        "SecurityException exception was thrown.", injectEventThrewSecurityException.get());
    assertTrue("Timed out!", latch.await(10, TimeUnit.SECONDS));
    assertTrue(injectEventWorked.get());
  }
}
 
Example #26
Source File: UiControllerImplIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectEmptyString() throws InterruptedException {
  final AtomicBoolean requestFocusSucceded = new AtomicBoolean(false);
  try (ActivityScenario<SendActivity> activityScenario =
      ActivityScenario.launch(SendActivity.class)) {
    activityScenario.onActivity(
        activity -> {
          final View view = activity.findViewById(R.id.send_data_to_call_edit_text);
          requestFocusSucceded.set(view.requestFocus());
          focusLatch.countDown();
        });

    assertTrue("requestFocus timed out!", focusLatch.await(2, TimeUnit.SECONDS));
    assertTrue("requestFocus failed.", requestFocusSucceded.get());

    getInstrumentation()
        .runOnMainSync(
            new Runnable() {
              @Override
              public void run() {
                try {
                  injectEventWorked.set(uiController.injectString(""));
                  latch.countDown();
                } catch (InjectEventSecurityException e) {
                  injectEventThrewSecurityException.set(true);
                }
              }
            });

    assertFalse(
        "SecurityException exception was thrown.", injectEventThrewSecurityException.get());
    assertTrue("Timed out!", latch.await(20, TimeUnit.SECONDS));
    assertTrue(injectEventWorked.get());
  }
}
 
Example #27
Source File: UiControllerImplIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void injectLargeString() throws InterruptedException {
  final AtomicBoolean requestFocusSucceded = new AtomicBoolean(false);

  try (ActivityScenario<SendActivity> activityScenario =
      ActivityScenario.launch(SendActivity.class)) {
    activityScenario.onActivity(
        activity -> {
          final View view = activity.findViewById(R.id.send_data_to_call_edit_text);
          Log.i("TEST", HumanReadables.describe(view));
          requestFocusSucceded.set(view.requestFocus());
          Log.i("TEST-post", HumanReadables.describe(view));

          focusLatch.countDown();
        });

    assertTrue("requestFocus timed out!", focusLatch.await(2, TimeUnit.SECONDS));
    assertTrue("requestFocus failed.", requestFocusSucceded.get());

    getInstrumentation()
        .runOnMainSync(
            new Runnable() {
              @Override
              public void run() {
                try {
                  injectEventWorked.set(
                      uiController.injectString("This is a string with 32 chars!!"));
                  latch.countDown();
                } catch (InjectEventSecurityException e) {
                  injectEventThrewSecurityException.set(true);
                }
              }
            });

    assertFalse(
        "SecurityException exception was thrown.", injectEventThrewSecurityException.get());
    assertTrue("Timed out!", latch.await(20, TimeUnit.SECONDS));
    assertTrue(injectEventWorked.get());
  }
}
 
Example #28
Source File: UiControllerImplIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void testInjectString() throws InterruptedException {
  final AtomicBoolean requestFocusSucceded = new AtomicBoolean(false);

  try (ActivityScenario<SendActivity> activityScenario =
      ActivityScenario.launch(SendActivity.class)) {
    activityScenario.onActivity(
        activity -> {
          final View view = activity.findViewById(R.id.send_data_to_call_edit_text);
          Log.i("TEST", HumanReadables.describe(view));
          requestFocusSucceded.set(view.requestFocus() && view.hasWindowFocus());
          Log.i("TEST-post", HumanReadables.describe(view));
          focusLatch.countDown();
        });

    assertTrue("requestFocus timed out!", focusLatch.await(2, TimeUnit.SECONDS));
    assertTrue("requestFocus failed.", requestFocusSucceded.get());

    getInstrumentation()
        .runOnMainSync(
            new Runnable() {
              @Override
              public void run() {
                try {
                  injectEventWorked.set(uiController.injectString("Hello! \n&*$$$"));
                  latch.countDown();
                } catch (InjectEventSecurityException e) {
                  injectEventThrewSecurityException.set(true);
                }
              }
            });

    assertFalse(
        "SecurityException exception was thrown.", injectEventThrewSecurityException.get());
    assertTrue("Timed out!", latch.await(20, TimeUnit.SECONDS));
    assertTrue(injectEventWorked.get());
  }
}
 
Example #29
Source File: IntentTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Espresso will not launch our activity for us, we must launch it via ActivityScenario.launch.
  ActivityScenario.launch(SendActivity.class);
  // Once initialized, Intento will begin recording and providing stubbing for intents.
  Intents.init();
  // Stubbing to block all external intents
  intending(not(isInternal())).respondWith(new ActivityResult(Activity.RESULT_OK, null));
}
 
Example #30
Source File: CoordinatesUtil.java    From android-test with Apache License 2.0 5 votes vote down vote up
static int[] getCoordinatesInMiddleOfSendButton(ActivityScenario activityScenario) {
  final int[] xyMiddle = new int[2];
  activityScenario.onActivity(
      new ActivityAction() {
        @Override
        public void perform(Activity activity) {
          final View sendButton = activity.findViewById(R.id.send_button);
          final int[] xy = new int[2];
          sendButton.getLocationOnScreen(xy);
          xyMiddle[0] = xy[0] + (sendButton.getWidth() / 2);
          xyMiddle[1] = xy[1] + (sendButton.getHeight() / 2);
        }
      });
  return xyMiddle;
}