Java Code Examples for android.support.test.espresso.assertion.ViewAssertions

The following are top voted examples for showing how to use android.support.test.espresso.assertion.ViewAssertions. 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: polling-station-app   File: TestElectionChoice.java   View source code 6 votes vote down vote up
@Test
    public void searchCityAndClick() throws Exception {
        List<Election> unfilteredList = electionActivity.getAdapter().getList();

        onView(withId(R.id.search)).perform(click());

        final Election toClick = unfilteredList.get(0);
        onView(withId(android.support.design.R.id.search_src_text)).perform(typeText(toClick.getPlace()));

        onView (withId (R.id.election_list)).check (ViewAssertions.matches (new Matchers().withListSize (1)));

        onData(instanceOf(Election.class))
                .inAdapterView(withId(R.id.election_list))
                .atPosition(0)
                .perform(click());
//        intended(hasComponent(MainActivity.class.getName()));
        onView(withId(R.id.app_bar)).check(new ViewAssertion() {
            @Override
            public void check(View view, NoMatchingViewException noViewFoundException) {
                assertEquals(((Toolbar) view).getTitle(), toClick.getKind());
                assertEquals(((Toolbar) view).getSubtitle(), toClick.getPlace());
            }
        });
    }
 
Example 2
Project: NumberPadTimePicker   File: NumberPadTimePickerDialogTest.java   View source code 6 votes vote down vote up
private static void verifyViewEnabledStates(TestCase test) {
    ViewInteraction[] buttonsInteractions = getButtonInteractions();
    ViewInteraction[] altButtonsInteractions = getAltButtonInteractions();
    for (int digit : test.sequence) {
        buttonsInteractions[digit]
                .check(ViewAssertions.matches(ViewMatchers.isEnabled()))
                .perform(ViewActions.click());
    }
    for (int i = 0; i < 10; i++) {
        buttonsInteractions[i].check(matchesIsEnabled(
                i >= test.numberKeysEnabledStart && i < test.numberKeysEnabledEnd));
        altButtonsInteractions[0].check(matchesIsEnabled(test.leftAltKeyEnabled));
        altButtonsInteractions[1].check(matchesIsEnabled(test.rightAltKeyEnabled));
    }

    Espresso.onView(ViewMatchers.withText(android.R.string.ok))
            .check(matchesIsEnabled(test.okButtonEnabled));

    ViewInteraction backspaceInteraction = Espresso.onView(
            ViewMatchers.withId(R.id.nptp_backspace));
    // Reset after each iteration by backspacing on the button just clicked.
    backspaceInteraction.check(matchesIsEnabled(true))
            .perform(ViewActions.longClick())
            .check(matchesIsEnabled(false));
}
 
Example 3
Project: smart-lens   File: InfoActivityTest.java   View source code 6 votes vote down vote up
@Test
public void checkRealApiResponse() throws Exception {
    WikiHelper.BASE_WIKI_URL = "https://en.wikipedia.org/w/";
    openActivity();

    //Wait for the api call
    Delay.startDelay(TestConfig.DELAY_FOR_REAL_API);
    onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());

    //Check if there are text?
    assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
            INFO_VIEW);
    onView(withId(R.id.wiki_page_tv)).check(ViewAssertions.matches(CustomMatchers.hasText()));
    onView(withId(R.id.wiki_page_iv)).check(ViewAssertions.matches(CustomMatchers.hasImage()));
    Delay.stopDelay();
}
 
Example 4
Project: smart-lens   File: InfoActivityTest.java   View source code 6 votes vote down vote up
@Test
public void checkImageApiResponseFail() throws Exception {
    MockWebServer mockWebServer = startMockWebServer();
    //Success response for the info api
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(200)
            .setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
                    com.kevalpatel2106.smartlens.test.R.raw.wiki_info_success_response)));
    //Fail response for the image api.
    mockWebServer.enqueue(new MockResponse().setResponseCode(500));
    openActivity();

    //Wait for mock api
    Delay.startDelay(TestConfig.DELAY_FOR_MOCK_API);
    onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());

    //Check if there are text?
    assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
            INFO_VIEW);
    onView(withId(R.id.wiki_page_tv)).check(ViewAssertions.matches(CustomMatchers.hasText()));
    onView(withId(R.id.wiki_page_iv)).check(ViewAssertions.matches(not(CustomMatchers.hasImage())));

    Delay.stopDelay();
    mockWebServer.shutdown();
}
 
Example 5
Project: Dryver   File: ActivityRegistrationTests.java   View source code 6 votes vote down vote up
/**
 * Simply inputs a presumably valid string for all EditTexts and attempts to select register.
 * Uses the mock ESController, so although the strings are validated, it is not actually pushed
 * to the ES server. Registration leads to the Selection Activity.
 *
 * @see ActivityRydeOrDryve
 */
@Test
public void TestRegister() throws InterruptedException {
    onView(withText("Registration")).check(ViewAssertions.matches(isDisplayed()));

    onView(withId(R.id.username_edittext)).perform(typeText(username));
    onView(withText(username)).check(ViewAssertions.matches(isDisplayed()));

    onView(withId(R.id.firstname_edittext)).perform(typeText(firstname));
    onView(withText(firstname)).check(ViewAssertions.matches(isDisplayed()));

    onView(withId(R.id.lastname_edittext)).perform(typeText(lastname));
    onView(withText(lastname)).check(ViewAssertions.matches(isDisplayed()));

    onView(withId(R.id.phone_edittext)).perform(typeText(phoneNumber));
    onView(withText(phoneNumber)).check(ViewAssertions.matches(isDisplayed()));

    onView(withId(R.id.email_edittext)).perform(typeText(email));
    onView(withText(email)).check(ViewAssertions.matches(isDisplayed()));

    onView(withText("Done")).perform(click());

    Thread.sleep(1000);

    intended(hasComponent(new ComponentName(getTargetContext(), ActivityRydeOrDryve.class)));
}
 
Example 6
Project: commitstrip-reader   File: ListFavoriteStripTest.java   View source code 6 votes vote down vote up
@Test
public void listFavoriteStrip_ListFavoriteActivity() throws Exception {

    Context context = InstrumentationRegistry.getTargetContext();

    Intent intent = new Intent(context, ListFavoriteActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(intent);

    // Check that the title is there.
    Espresso.onView(ViewMatchers.withId(R.id.recyclerView))
            .check(ViewAssertions.matches(
                    RecyclerViewUtil.atPosition(0,
                            ViewMatchers.hasDescendant(
                                    ViewMatchers.withText(mStrip.getTitle())
                            )
                    )
            ));
}
 
Example 7
Project: commitstrip-reader   File: AddFavoriteStripTest.java   View source code 6 votes vote down vote up
private void addAndCheckFavorite(int idFavButton) throws Exception {

        // Check that the title is there.
        Espresso.onView(ViewMatchers.withId(R.id.title)).check(
                ViewAssertions.matches(ViewMatchers.withText(mStrip.getTitle()))
        );

        // Add in favorite
        Espresso.onView(ViewMatchers.withId(idFavButton)).perform(ViewActions.click());

        // Check if we correctly register the strip in the database
        Integer numberRow =
                mDatabase
                        .count()
                        .from(StripDaoEntity.class)
                        .where(StripDaoEntity.ID.eq(mStrip.getId()))
                        .and(StripDaoEntity.IS_FAVORITE.eq(true))
                        .get().call();

        if (numberRow != 1) {
            throw new AssertionError(
                    "[AddFavoriteStripTest] Strips have not been added in favorite");
        }
    }
 
Example 8
Project: material-components-android   File: BottomSheetBehaviorTest.java   View source code 6 votes vote down vote up
@Test
@MediumTest
public void testSwipeDownToHide() {
  Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
      .perform(
          DesignViewActions.withCustomConstraints(
              ViewActions.swipeDown(), ViewMatchers.isDisplayingAtLeast(5)));
  registerIdlingResourceCallback();
  try {
    Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
        .check(ViewAssertions.matches(not(ViewMatchers.isDisplayed())));
    assertThat(getBehavior().getState(), is(BottomSheetBehavior.STATE_HIDDEN));
  } finally {
    unregisterIdlingResourceCallback();
  }
}
 
Example 9
Project: material-components-android   File: BottomSheetBehaviorTest.java   View source code 6 votes vote down vote up
@Test
@MediumTest
public void testSwipeUpToExpand() {
  Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
      .perform(
          DesignViewActions.withCustomConstraints(
              new GeneralSwipeAction(
                  Swipe.FAST,
                  GeneralLocation.VISIBLE_CENTER,
                  new CoordinatesProvider() {
                    @Override
                    public float[] calculateCoordinates(View view) {
                      return new float[] {view.getWidth() / 2, 0};
                    }
                  },
                  Press.FINGER),
              ViewMatchers.isDisplayingAtLeast(5)));
  registerIdlingResourceCallback();
  try {
    Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
        .check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    assertThat(getBehavior().getState(), is(BottomSheetBehavior.STATE_EXPANDED));
  } finally {
    unregisterIdlingResourceCallback();
  }
}
 
Example 10
Project: material-components-android   File: BottomSheetBehaviorTest.java   View source code 6 votes vote down vote up
private void checkSetState(final int state, Matcher<View> matcher) throws Throwable {
  registerIdlingResourceCallback();
  try {
    activityTestRule.runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            getBehavior().setState(state);
          }
        });
    Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
        .check(ViewAssertions.matches(matcher));
    assertThat(getBehavior().getState(), is(state));
  } finally {
    unregisterIdlingResourceCallback();
  }
}
 
Example 11
Project: android-testing   File: EspressoTest.java   View source code 6 votes vote down vote up
public void testFormSending() {
    //SystemClock.sleep(2000);
    // Fills the text into form
    Espresso.onView(ViewMatchers.withId(R.id.name_edittext))
            .perform(ViewActions.typeTextIntoFocusedView("Jana Moudra"))
            .check(ViewAssertions.matches(ViewMatchers.withText("Jana Moudra")));

    //SystemClock.sleep(2000);
    // Opens new Activity
    Espresso.onView(ViewMatchers.withId(R.id.name_btn))
            .perform(ViewActions.click());

    //SystemClock.sleep(2000);
    // Checks the text
    Espresso.onView(ViewMatchers.withId(R.id.name_textview))
            .check(ViewAssertions.matches(ViewMatchers.withText("Jana Moudra")));
}
 
Example 12
Project: mpos-ui.android.paybutton   File: TransactionActivityTest.java   View source code 6 votes vote down vote up
public void testApplicationSelection() {
    initWithAmount(113.73);
    StatefulTransactionProviderProxyIdlingResource idlingResource = new StatefulTransactionProviderProxyIdlingResource(false, true);
    Espresso.registerIdlingResources(idlingResource);
    Espresso.onData(Matchers.hasToString(Matchers.equalToIgnoringWhiteSpace("Mocked VISA")))
            .inAdapterView(ViewMatchers.withId(R.id.mpu_selection_list_view))
            .perform(ViewActions.click());

    Espresso.unregisterIdlingResources(idlingResource);

    idlingResource = new StatefulTransactionProviderProxyIdlingResource();
    Espresso.registerIdlingResources(idlingResource);


    Espresso.onView(ViewMatchers.withId(R.id.mpu_summary_account_number_view))
            .check(ViewAssertions.matches(ViewMatchers.withText("************0119")));

    Espresso.unregisterIdlingResources(idlingResource);
}
 
Example 13
Project: mpos-ui.android.paybutton   File: TransactionActivityTest.java   View source code 6 votes vote down vote up
public void testSignatureActivityIsShown() {
    initWithAmount(108.20);
    StatefulTransactionProviderProxyIdlingResource idlingResource = new StatefulTransactionProviderProxyIdlingResource(true, false);
    Espresso.registerIdlingResources(idlingResource);

    //fake a signature by triggering a touch event
    Espresso.onView(ViewMatchers.withId(R.id.mpu_signature_view))
            .perform(ViewActions.click());

    Espresso.onView(ViewMatchers.withId(R.id.mpu_continue_button))
            .perform(ViewActions.click());

    Espresso.unregisterIdlingResources(idlingResource);

    idlingResource = new StatefulTransactionProviderProxyIdlingResource();
    Espresso.registerIdlingResources(idlingResource);
    Espresso.onView(ViewMatchers.withId(R.id.mpu_summary_scheme_view))
            .check(ViewAssertions.matches(ViewMatchers.isDisplayed()));

    Espresso.unregisterIdlingResources(idlingResource);
}
 
Example 14
Project: AndroidEspressoIdlingResourcePlayground   File: FirstActivityEspressoTest.java   View source code 6 votes vote down vote up
@Test
public void firstActivityTest() throws InterruptedException {
    secondActivityCreatedIdlingResource = new SecondActivityCreatedIdlingResource();

    GlobalApplication.activityEventStream().
            subscribeOn(Schedulers.newThread())
                     .observeOn(AndroidSchedulers.mainThread())
                     .subscribe(secondActivityCreatedIdlingResource);

    // Click on button that simulates long network call and after success goes to SecondActivity
    onView(withId(R.id.button1OnFirstActivity)).perform(click());

    // Wait until SecondActivity is created
    registerIdlingResources(secondActivityCreatedIdlingResource);

    // Validate label on SecondActivity
    onView(withText("Second Activity")).check(ViewAssertions.matches(isDisplayed()));
}
 
Example 15
Project: IBM-Ready-App-for-Telecommunications   File: TextPageTest.java   View source code 6 votes vote down vote up
/**
 * Tests that the Current Cycle UI updates on the Text page after changing base text plan
 */
@Test
public void testTextCurrentCycleUpdate() {
    onView(withChild(withText(textTabText))).perform(click());
    SystemClock.sleep(1000);

    Matcher<View> usageView = allOf(withId(R.id.bottom_left_text), isDescendantOfA(withId(R.id.my_text_recyclerview)), isDescendantOfA(withId(R.id.cycle_viewer)));
    Matcher<View> progressBar = allOf(withId(R.id.progress_bar), isDescendantOfA(withId(R.id.my_text_recyclerview)), isDescendantOfA(withId(R.id.cycle_viewer)));


    // Get initial text values out of String
    String usedTexts = getText(usageView).split("\\/")[0];
    String totalTexts = getText(usageView).split("\\/")[1].split(" ")[0];
    float usedTextsFloat = Float.parseFloat(usedTexts);
    int totalTextsInt = Integer.parseInt(totalTexts);
    int percentUsed = (int)(((double)usedTextsFloat/ (double)totalTextsInt) * 100.0);
    onView(progressBar).check(ViewAssertions.matches(withProgress(percentUsed)));

    // Increase the number of texts and confirm changes in Current Cycle
    onView(allOf(withId(R.id.up_arrow), isDescendantOfA(withId(R.id.my_text_recyclerview)))).perform(click());
    onView(allOf(withId(R.id.confirm), isDescendantOfA(withId(R.id.my_text_recyclerview)))).perform(click());

    totalTextsInt += textInterval;
    String newString = usedTextsFloat+"/"+totalTextsInt+" SMS";
    onView(usageView).check(matches(withText(newString)));
}
 
Example 16
Project: BioStar2Android   File: ExtTest.java   View source code 6 votes vote down vote up
public static int checkListCount(final int viewId) {
    final Integer[] result = {0};
    onView(withId(viewId)).check(ViewAssertions.matches(new TypeSafeMatcher<View>() {
        @Override
        public boolean matchesSafely(View view) {
            ListView listView = (ListView) view;
            result[0] = listView.getCount();
            return true;
        }

        @Override
        public void describeTo(Description description) {

        }
    }));
    return result[0];
}
 
Example 17
Project: BioStar2Android   File: UserTestUtil.java   View source code 6 votes vote down vote up
public static void checkUserList(final int viewId) {
    onView(withId(viewId)).check(ViewAssertions.matches(new TypeSafeMatcher<View>() {
        @Override
        public boolean matchesSafely(View view) {
            ListView listView = (ListView) view;
            try {
                ListUser user = (ListUser) listView.getItemAtPosition(0);
            } catch (Exception e) {
                Log.e(TAG, "fail Not match UserList");
                return false;
            }
            //  ListUser user = (ListUser) listView.getItemAtPosition(0);
            return true;
        }

        @Override
        public void describeTo(Description description) {

        }
    }));
}
 
Example 18
Project: BioStar2Android   File: UserTestUtil.java   View source code 6 votes vote down vote up
public static void saveUserID() {
        Log.e(TAG, "case: User/User 등록/UserID입력/1/3. User ID를 선택한다.");
        w(1000);
        onView(withId(R.id.user_id)).perform(ViewActions.click());
        w(1000);
//        onView(withId(R.id.user_id))
//                .check(ViewAssertions.matches(ViewMatchers.hasImeAction(EditorInfo.IME_ACTION_DONE)));
        onView(withId(R.id.user_id))
                .check((ViewAssertions.matches(ExtTest.hasImeInputType(InputType.TYPE_CLASS_NUMBER))));
        Log.e(TAG, "result: 3) 숫자 키패드가 표시되며 숫자만 입력 가능한지 확인한다.");

        Log.e(TAG, "case: User/User 등록/UserID입력/2/1. 최대 입력값을 입력한다. 4294967294");
        w(1000);
        onView(withId(R.id.user_id)).perform(ViewActions.typeText("4294967294")); //id
        w(1000);
        onView(withId(R.id.user_id)).perform(ViewActions.closeSoftKeyboard());
    }
 
Example 19
Project: BioStar2Android   File: UserTestUtil.java   View source code 6 votes vote down vote up
public static void saveName() {
    Log.e(TAG, "case: User/User 등록/Name입력/1~4 해당 데이터를 입력한다./영문+국문+숫자+특수문자 혼용 9부터 49자");
    w(1000);
    onView(withId(R.id.name)).perform(ViewActions.click());
    ExtTest.delEditText(R.id.name);
    onView(withId(R.id.name)).perform(ViewActions.typeText("[email protected]#$^&*()_abcdefghijklmopqrst7810"));
    onView(withId(R.id.name)).perform(ViewActions.typeText("UVWXYX7899999999999999999"));
    int length = ExtTest.getTextFromEditTextView(R.id.name).length();
    if (length > 48) {
        onView(withId(R.id.name))
                .check((ViewAssertions.matches(ExtTest.setResult(false))));
    } else {
        Log.e(TAG, "result: User/User 등록/Name입력/1~4 해당 데이터를 입력한다./1. 최대 48자 초과 시 입력되지 않음을 확인한다.");
    }
    onView(withId(R.id.name)).perform(ViewActions.closeSoftKeyboard());
}
 
Example 20
Project: BioStar2Android   File: UserTest.java   View source code 6 votes vote down vote up
private void inputOperator() {
        Log.e(TAG, "start: inputOperator");
        UserTestUtil.addUserCheck(mActivityRule.getActivity().getResources().getString(R.string.new_user));
        Log.e(TAG, "case: User/User 등록/operator/BioStar Operator 초기값을 확인한다.");
        onView(withId(R.id.operator)).check(ViewAssertions.matches(ViewMatchers.withText(mActivityRule.getActivity().getResources().getString(R.string.none))));
//        onView(isRoot()).perform(ExtTest.waitInvisibleGoneId(R.id.operator_expand, 3000));
        Log.e(TAG, "result: 초기값은 None으로 출력된다.");

        UserTestUtil.selectOperation(0);
        UserTestUtil.selectOperation(-1);
        UserTestUtil.selectOperation(0);

        UserTestUtil.saveUserID();
//        UserTestUtil.inputEdit(R.id.login_id, 32, R.id.login_id_edit);
        UserTestUtil.inputPassword();
        onView(withId(R.id.action_save)).perform(ViewActions.click());
        w(1000);
        ExtTest.checkPopupType(false, true, Popup.PopupType.ALERT);
        Log.e(TAG, "result: 입력한 특수기호 표시,입력한 Password로 설정이 가능해야한다.");
        UserTestUtil.searchDeleteUserID("4294967294", false);
        Log.e(TAG, "end: inputOperator");
    }
 
Example 21
Project: BioStar2Android   File: UserTest.java   View source code 6 votes vote down vote up
private void inputGroup() {
        Log.e(TAG, "start: inputGroup");
        UserTestUtil.addUserCheck(mActivityRule.getActivity().getResources().getString(R.string.new_user));


        Log.e(TAG, "case: User/User 등록/operator/BioStar Operator 초기값을 확인한다.");
        onView(withId(R.id.operator)).check(ViewAssertions.matches(ViewMatchers.withText(mActivityRule.getActivity().getResources().getString(R.string.none))));
//        onView(isRoot()).perform(ExtTest.waitInvisibleGoneId(R.id.operator_expand, 3000));
        Log.e(TAG, "result: 초기값은 None으로 출력된다.");

        UserTestUtil.selectOperation(0);
        UserTestUtil.selectOperation(-1);
        UserTestUtil.selectOperation(0);

        UserTestUtil.saveUserID();
//        UserTestUtil.inputEdit(R.id.login_id, 32, R.id.login_id_edit);
        UserTestUtil.inputPassword();
        onView(withId(R.id.action_save)).perform(ViewActions.click());
        w(1000);
        ExtTest.checkPopupType(false, true, Popup.PopupType.ALERT);
        Log.e(TAG, "result: 입력한 특수기호 표시,입력한 Password로 설정이 가능해야한다.");
        UserTestUtil.searchDeleteUserID("4294967294", false);
        Log.e(TAG, "end: inputGroup");
    }
 
Example 22
Project: PrettyBundle   File: InjectPrimaryTypeExtrasFragmentTest.java   View source code 6 votes vote down vote up
public void testStartPrimaryTypeDisplayWithExtras() throws Exception {
    final String integerExtra = "1";
    final String longExtra = "2";
    final String floatExtra = "3.4";
    final String doubleExtra = "5.6";
    final String stringExtra = "String value";
    final String charSequenceExtra = "CharSequence value";

    Espresso.onView(ViewMatchers.withText(integerExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(longExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(floatExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(doubleExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText("true")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(stringExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(charSequenceExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
 
Example 23
Project: PrettyBundle   File: InjectArrayExtrasTest.java   View source code 6 votes vote down vote up
public void testArrayExtrasDisplay() throws Exception {
    // Open TestArrayActivity
    Espresso.onView(ViewMatchers.withText(R.string.test_array_extras)).perform(ViewActions.click());

    // Verify result.
    // int arrays
    Espresso.onView(ViewMatchers.withText("{1,2,3}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    // long arrays
    Espresso.onView(ViewMatchers.withText("{4,5,6}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    // float arrays
    Espresso.onView(ViewMatchers.withText("{4.1,5.1,6.1}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    // double arrays
    Espresso.onView(ViewMatchers.withText("{7.2,8.2,9.2}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    // boolean arrays
    Espresso.onView(ViewMatchers.withText("{true,false,false,true}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    // string arrays
    Espresso.onView(ViewMatchers.withText("{One,Two,Three}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    // people
    Espresso.onView(ViewMatchers.withText("{{name='p1',age=18},{name='p2',age=19}}")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));

}
 
Example 24
Project: PrettyBundle   File: InjectPrimaryTypeExtrasFragment4Test.java   View source code 6 votes vote down vote up
public void testStartPrimaryTypeDisplayWithExtras() throws Exception {
    final String integerExtra = "1";
    final String longExtra = "2";
    final String floatExtra = "3.4";
    final String doubleExtra = "5.6";
    final String stringExtra = "String value";
    final String charSequenceExtra = "CharSequence value";

    Espresso.onView(ViewMatchers.withText(integerExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(longExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(floatExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(doubleExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText("true")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(stringExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    Espresso.onView(ViewMatchers.withText(charSequenceExtra)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
 
Example 25
Project: polling-station-app   File: TestManualInputActivity.java   View source code 5 votes vote down vote up
@Test
public void testInvalidData() {
    closeSoftKeyboard();
    onView(withId(R.id.submit_button)).perform(click());
    onView(ViewMatchers.withId(R.id.doc_num))
            .check(ViewAssertions.matches(
                    ViewMatchers.hasErrorText(
                            activityRule.getActivity().getString(R.string.errInputDocNum))));
}
 
Example 26
Project: polling-station-app   File: TestElectionChoice.java   View source code 5 votes vote down vote up
@Test
public void performSearch() throws Exception {
    List<Election> unfilteredList = electionActivity.getAdapter().getList();

    onView (withId (R.id.election_list)).check (ViewAssertions.matches (new Matchers().withListSize (unfilteredList.size())));
    onView(withId(R.id.search)).perform(click());
    onView(withId(android.support.design.R.id.search_src_text)).perform(typeText("something"));

    List<Election> filteredList = electionActivity.getAdapter().getList();
    onView (withId (R.id.election_list)).check (ViewAssertions.matches (new Matchers().withListSize (filteredList.size())));
}
 
Example 27
Project: NumberPadTimePicker   File: NumberPadTimePickerDialogTest.java   View source code 5 votes vote down vote up
@Test
public void verifyInitialViewEnabledStates() {
    openTimePicker();
    Espresso.onView(ViewMatchers.withId(R.id.nptp_input_time)).check(
            ViewAssertions.matches(ViewMatchers.withText("")));
    // Check that the am/pm view is set to the correct visibility.
    //
    // Rather than use the isDisplayed() matcher, which, on top of matching the view to a
    // View.VISIBLE state, matches the view to being drawn with visible bounds, we use
    // the withEffectiveVisibility() matcher to match only the former criterion.
    Espresso.onView(ViewMatchers.withId(R.id.nptp_input_ampm)).check(
            ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(mInitiallyIn24HourMode ?
                    ViewMatchers.Visibility.GONE : ViewMatchers.Visibility.VISIBLE)));
    if (!mInitiallyIn24HourMode) {
        Espresso.onView(ViewMatchers.withId(R.id.nptp_input_ampm)).check(
                ViewAssertions.matches(isNthChildOf(
                        ViewMatchers.withId(R.id.nptp_input_time_container),
                        mLocaleModel.isAmPmWrittenBeforeTime() ? 0 : 1)));
    }
    Espresso.onView(ViewMatchers.withId(R.id.nptp_backspace)).check(
            matchesIsEnabled(false));
    // We can easily manually verify whether the divider is focused, so it's not worth the
    // trouble of writing a test.
    for (int i = 0; i < 10; i++) {
        Espresso.onView(withDigit(i)).check(matchesIsEnabled(mInitiallyIn24HourMode || i > 0));
    }
    Espresso.onView(ViewMatchers.withId(R.id.nptp_text9)).check(matchesIsEnabled(false));
    Espresso.onView(ViewMatchers.withId(R.id.nptp_text11)).check(matchesIsEnabled(false));
    Espresso.onView(ViewMatchers.withText(android.R.string.ok)).check(matchesIsEnabled(false));
}
 
Example 28
Project: NumberPadTimePicker   File: NumberPadTimePickerDialogTest.java   View source code 5 votes vote down vote up
/**
 * @param enabled Whether the view should be matched to be enabled or not.
 * @return A {@link ViewAssertion} that asserts that a view should be matched
 *         to be enabled or disabled.
 */
private static ViewAssertion matchesIsEnabled(boolean enabled) {
    // TODO: When we're comfortable with the APIs, we can statically import them and
    // make direct calls to these methods and cut down on the verbosity, instead of
    // writing helper methods that wrap these APIs.
    return ViewAssertions.matches(enabled ? ViewMatchers.isEnabled() : Matchers.not(ViewMatchers.isEnabled()));
}
 
Example 29
Project: smart-lens   File: InfoActivityTest.java   View source code 5 votes vote down vote up
@Test
public void checkInfoFoundApiResponse() throws Exception {
    MockWebServer mockWebServer = startMockWebServer();
    //Success response for the info api
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(200)
            .setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
                    com.kevalpatel2106.smartlens.test.R.raw.wiki_info_success_response)));
    //Success response for the image api.
    mockWebServer.enqueue(new MockResponse()
            .setResponseCode(200)
            .setBody(getStringFromFile(InstrumentationRegistry.getInstrumentation().getContext(),
                    com.kevalpatel2106.smartlens.test.R.raw.wiki_image_success_response)));
    openActivity();

    //Wait for mock api
    Delay.startDelay(TestConfig.DELAY_FOR_REAL_API);
    onView(withId(R.id.root_view)).perform(ViewActions.closeSoftKeyboard());

    //Check if there are text?
    assertTrue(mWikiFragmentFragmentTestRule.getActivity().mViewFlipper.getDisplayedChild() ==
            INFO_VIEW);
    onView(withId(R.id.wiki_page_tv)).check(ViewAssertions.matches(CustomMatchers.hasText()));
    onView(withId(R.id.wiki_page_iv)).check(ViewAssertions.matches(CustomMatchers.hasImage()));

    Delay.stopDelay();
    mockWebServer.shutdown();
}
 
Example 30
Project: Dryver   File: ActivityOpeningPageTests.java   View source code 5 votes vote down vote up
/**
 * Tests selecting the registration button whcich goes to the registration Activity
 * @see ActivityRegistration
 */
@Test
public void TestSelectRegistration() {
    onView(withText("New user?")).check(ViewAssertions.matches(isDisplayed()));

    onView(withText("Sign Up")).perform(click());

    intended(hasComponent(new ComponentName(getTargetContext(), ActivityRegistration.class)));
}
 
Example 31
Project: commitstrip-reader   File: SwapStripTest.java   View source code 5 votes vote down vote up
@Test
public void swapStrip_StripActivity() {

    Context context = InstrumentationRegistry.getTargetContext();
    Intent intent = new Intent(context, StripActivity.class);
        intent.putExtras (StripActivity.newInstance(Long.valueOf(SampleStrip.STRIP_ID_ONE)));
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);

    context.startActivity(intent);

    // Check that the title is there.
    Espresso.onView(ViewMatchers.withId(R.id.title)).check(
            ViewAssertions.matches(ViewMatchers.withText(SampleStrip.STRIP_ID_ONE_TITLE)));

    // Check that we can use swipe left, the goal is just to test that we have no error
    Espresso.onView(ViewMatchers.withId(R.id.strip)).perform(
            ViewActions.swipeRight());

    // Check that the title is always there.
    Espresso.onView(ViewMatchers.withId(R.id.title)).check(
            ViewAssertions.matches(ViewMatchers.withText(SampleStrip.STRIP_ID_ONE_TITLE)));

    // Check that we can use swipe left
    Espresso.onView(ViewMatchers.withId(R.id.strip)).perform(
            ViewActions.swipeLeft());

    // Expect a new strip to be displayed
    Espresso.onView(ViewMatchers.withId(R.id.title)).check(
            ViewAssertions.matches(ViewMatchers.withText(SampleStrip.STRIP_ID_TWO_TITLE)));
}
 
Example 32
Project: material-components-android   File: BottomSheetBehaviorTest.java   View source code 5 votes vote down vote up
@Test
@MediumTest
public void testHalfExpandedToExpanded() throws Throwable {
  getBehavior().setFitToContents(false);
  checkSetState(BottomSheetBehavior.STATE_HALF_EXPANDED, ViewMatchers.isDisplayed());
  Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
      .perform(
          DesignViewActions.withCustomConstraints(
              new GeneralSwipeAction(
                  Swipe.FAST,
                  GeneralLocation.VISIBLE_CENTER,
                  new CoordinatesProvider() {
                    @Override
                    public float[] calculateCoordinates(View view) {
                      return new float[] {view.getWidth() / 2, 0};
                    }
                  },
                  Press.FINGER),
              ViewMatchers.isDisplayingAtLeast(5)));
  registerIdlingResourceCallback();
  try {
    Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
        .check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    assertThat(getBehavior().getState(), is(BottomSheetBehavior.STATE_EXPANDED));
  } finally {
    unregisterIdlingResourceCallback();
  }
}
 
Example 33
Project: material-components-android   File: BottomSheetBehaviorTest.java   View source code 5 votes vote down vote up
@Test
@MediumTest
public void testCollapsedToExpanded() throws Throwable {
  getBehavior().setFitToContents(false);
  checkSetState(BottomSheetBehavior.STATE_COLLAPSED, ViewMatchers.isDisplayed());
  Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
      .perform(
          DesignViewActions.withCustomConstraints(
              new GeneralSwipeAction(
                  Swipe.FAST,
                  GeneralLocation.VISIBLE_CENTER,
                  new CoordinatesProvider() {
                    @Override
                    public float[] calculateCoordinates(View view) {
                      return new float[] {view.getWidth() / 2, 0};
                    }
                  },
                  Press.FINGER),
              ViewMatchers.isDisplayingAtLeast(5)));
  registerIdlingResourceCallback();
  try {
    Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
        .check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    assertThat(getBehavior().getState(), is(BottomSheetBehavior.STATE_EXPANDED));
  } finally {
    unregisterIdlingResourceCallback();
  }
}
 
Example 34
Project: material-components-android   File: BottomSheetBehaviorTest.java   View source code 5 votes vote down vote up
@Test
@MediumTest
public void testDynamicContent() throws Throwable {
  registerIdlingResourceCallback();
  try {
    activityTestRule.runOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            ViewGroup.LayoutParams params = getBottomSheet().getLayoutParams();
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            getBottomSheet().setLayoutParams(params);
            View view = new View(getBottomSheet().getContext());
            int size = getBehavior().getPeekHeight() * 2;
            getBottomSheet().addView(view, new ViewGroup.LayoutParams(size, size));
            assertThat(getBottomSheet().getChildCount(), is(1));
            // Shrink the content height.
            ViewGroup.LayoutParams lp = view.getLayoutParams();
            lp.height = (int) (size * 0.8);
            view.setLayoutParams(lp);
            // Immediately expand the bottom sheet.
            getBehavior().setState(BottomSheetBehavior.STATE_EXPANDED);
          }
        });
    Espresso.onView(ViewMatchers.withId(R.id.bottom_sheet))
        .check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
    assertThat(getBehavior().getState(), is(BottomSheetBehavior.STATE_EXPANDED));
    // Make sure that the bottom sheet is not floating above the bottom.
    assertThat(getBottomSheet().getBottom(), is(getCoordinatorLayout().getBottom()));
  } finally {
    unregisterIdlingResourceCallback();
  }
}
 
Example 35
Project: material-components-android   File: BottomSheetDialogTest.java   View source code 5 votes vote down vote up
@Test
public void testShortDialog() throws Throwable {
  activityTestRule.runOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          showDialog();
        }
      });
  // This ensures that the views are laid out before assertions below
  Espresso.onView(ViewMatchers.withId(R.id.design_bottom_sheet))
      .perform(setTallPeekHeight())
      .check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
  activityTestRule.runOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          FrameLayout bottomSheet = dialog.findViewById(R.id.design_bottom_sheet);
          CoordinatorLayout coordinator = (CoordinatorLayout) bottomSheet.getParent();
          BottomSheetBehavior<FrameLayout> behavior = BottomSheetBehavior.from(bottomSheet);
          assertThat(bottomSheet, is(notNullValue()));
          assertThat(coordinator, is(notNullValue()));
          assertThat(behavior, is(notNullValue()));
          // This bottom sheet is shorter than the peek height
          assertThat(bottomSheet.getHeight(), is(lessThan(behavior.getPeekHeight())));
          // Confirm that the bottom sheet is bottom-aligned
          assertThat(bottomSheet.getTop(), is(coordinator.getHeight() - bottomSheet.getHeight()));
        }
      });
}
 
Example 36
Project: espresso-errortext-matcher   File: ApplicationTest.java   View source code 5 votes vote down vote up
@Test
public void checkWithRawText() {
  Espresso
      .onView(ViewMatchers.withId(R.id.email_sign_in_button))
      .perform(ViewActions.click());
  Espresso
      .onView(ViewMatchers.withId((R.id.email)))
      .check(ViewAssertions.matches(ErrorTextMatchers.withErrorText("This field is required")));
}
 
Example 37
Project: espresso-errortext-matcher   File: ApplicationTest.java   View source code 5 votes vote down vote up
@Test
public void checkWithStringId() {
  Espresso
      .onView(ViewMatchers.withId((R.id.email)))
      .perform(ViewActions.typeText("invalid"));
  Espresso
      .onView(ViewMatchers.withId(R.id.email_sign_in_button))
      .perform(ViewActions.click());
  Espresso
      .onView(ViewMatchers.withId((R.id.email)))
      .check(ViewAssertions.matches(ErrorTextMatchers.withErrorText(R.string.error_invalid_email)));
}
 
Example 38
Project: espresso-errortext-matcher   File: ApplicationTest.java   View source code 5 votes vote down vote up
@Test
public void checkWithMatcher() {
  Espresso
      .onView(ViewMatchers.withId((R.id.email)))
      .perform(ViewActions.typeText("[email protected]"));
  Espresso
      .onView(ViewMatchers.withId((R.id.password)))
      .perform(ViewActions.typeText("foo"));
  Espresso
      .onView(ViewMatchers.withId(R.id.email_sign_in_button))
      .perform(ViewActions.click());
  Espresso
      .onView(ViewMatchers.withId((R.id.password)))
      .check(ViewAssertions.matches(ErrorTextMatchers.withErrorText(Matchers.containsString("too short"))));
}
 
Example 39
Project: grocery-reminder   File: RemindersActivityTest.java   View source code 5 votes vote down vote up
@Test
public void testGivenAReminderHasBeenAddedWhenTheClearIconIsTappedThenTheReminderIsDismissed() {
    addArbitraryReminder();

    onView(withId(R.id.clear_icon)).perform(click());

    onView(withText(ARBITRARY_REMINDER)).check(ViewAssertions.doesNotExist());
}
 
Example 40
Project: grocery-reminder   File: RemindersActivityTest.java   View source code 5 votes vote down vote up
@Test
public void testGivenAReminderHashBeenAddedWhenItIsSwipedLeftThenItIsDismissed() {
    addArbitraryReminder();
    onView(withText(ARBITRARY_REMINDER)).check(matches(isDisplayed()));

    onView(withText(ARBITRARY_REMINDER)).perform(swipeLeft());

    onView(withText(ARBITRARY_REMINDER)).check(ViewAssertions.doesNotExist());
}