下面列出了android.support.test.espresso.action.ViewActions#android.support.test.espresso.assertion.ViewAssertions 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
});
}
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));
}
@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()));
}
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()));
}
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()));
}
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()));
}
@Test
public void adapterViewSimpleTest() {
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button3)).perform(ViewActions.click());
Espresso.onData(Matchers.allOf(Matchers
.is(Matchers.instanceOf(String.class)), Matchers.is("HaHa")))
.perform(ViewActions.click());
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button))
.check(ViewAssertions.matches(ViewMatchers.withText(Matchers.containsString("HaHa"))));
}
@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))));
}
@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())));
}
@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));
}
/**
* @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()));
}
@Test
public void secondActivityTest() throws InterruptedException {
DecoratedLongRunningService decoratedLongRunningService = new DecoratedLongRunningService();
registerIdlingResources(decoratedLongRunningService);
secondActivity.get().setService(decoratedLongRunningService);
onView(withId(R.id.button1OnSecondActivity)).perform(click());
onView(withText("SUCCESS")).check(ViewAssertions.matches(isDisplayed()));
}
public void testStartActivityTestStringExtra2WithExtras() throws Exception {
final String extra1 = "Giang";
final String extra2 = "Nguyen";
Espresso.onView(ViewMatchers.withHint(R.string.string_extra_1)).perform(ViewActions.typeText(extra1), ViewActions.pressImeActionButton());
Espresso.onView(ViewMatchers.withHint(R.string.string_extra_2)).perform(ViewActions.typeText(extra2), ViewActions.pressImeActionButton());
Espresso.onView(ViewMatchers.withText(R.string.submit)).perform(ExtViewActions.waitForSoftKeyboard(), ViewActions.click());
Espresso.onView(ViewMatchers.withText(extra1)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withText(extra2)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
public void testStartActivityTestStringExtra2UsingDefaultValue() throws Exception {
final String extra2 = "Nguyen";
Espresso.onView(ViewMatchers.withHint(R.string.string_extra_2)).perform(ViewActions.typeText(extra2));
Espresso.closeSoftKeyboard();
Espresso.onView(ViewMatchers.withText(R.string.submit)).perform(ExtViewActions.waitForSoftKeyboard(), ViewActions.click());
Espresso.onView(ViewMatchers.withText("Default")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withText(extra2)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
public void testStartPrimaryTypeDisplayWithExtras() throws Exception {
getInstrumentation().runOnMainSync(new Runnable() {
@Override public void run() {
((CheckBox) activity.findViewById(R.id.cbBoolean)).setChecked(true);
}
});
final String integerExtra = "1";
Espresso.onView(ViewMatchers.withHint(R.string.hint_int)).perform(ViewActions.typeText(integerExtra), ViewActions.pressImeActionButton());
final String longExtra = "2";
Espresso.onView(ViewMatchers.withHint(R.string.hint_long)).perform(ViewActions.typeText(longExtra), ViewActions.pressImeActionButton());
final String floatExtra = "3.4";
Espresso.onView(ViewMatchers.withHint(R.string.hint_float)).perform(ViewActions.typeText(floatExtra), ViewActions.pressImeActionButton());
final String doubleExtra = "5.6";
Espresso.onView(ViewMatchers.withHint(R.string.hint_double)).perform(ViewActions.typeText(doubleExtra), ViewActions.pressImeActionButton());
final String stringExtra = "String value";
Espresso.onView(ViewMatchers.withHint(R.string.hint_string)).perform(ViewActions.typeText(stringExtra), ViewActions.pressImeActionButton());
final String charSequenceExtra = "CharSequence value";
Espresso.onView(ViewMatchers.withHint(R.string.hint_char_sequence)).perform(ViewActions.typeText(charSequenceExtra), ViewActions.pressImeActionButton());
Espresso.closeSoftKeyboard();
Espresso.onView(ViewMatchers.withText(R.string.submit)).perform(ExtViewActions.waitForSoftKeyboard(), ViewActions.scrollTo(), ViewActions.click());
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()));
}
@Test
public void ViewAssertions() {
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button)).perform(ViewActions.click());
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button2)).check(ViewAssertions.matches(ViewMatchers.withText("HaHa")));
}
@Test
public void notDisplayed() {
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button)).
check(ViewAssertions.matches(Matchers.not(ViewMatchers.isDisplayed())));
}
@Test
public void checkNotExist() {
Espresso.onView(ViewMatchers.withId(R.id.button)).check(ViewAssertions.doesNotExist());
}
private void hassActivityTest(String url, String password) {
sleep(1000);
final HassActivity activity = mActivityTestRule.getActivity();
// Check prefs
PREFS = Utils.getPrefs(activity);
assertFalse(PREFS.contains(Common.PREF_HASS_URL_KEY));
assertFalse(PREFS.contains(Common.PREF_HASS_PASSWORD_KEY));
// Login
ViewInteraction textInput = onView(
allOf(withId(R.id.url_input),
childAtPosition(childAtPosition(withId(R.id.url_input_layout), 0), 0),
isDisplayed()));
textInput.perform(replaceText(url), closeSoftKeyboard());
if (password != null) {
ViewInteraction passwordInput = onView(
allOf(withId(R.id.password_input),
childAtPosition(childAtPosition(withId(R.id.password_input_layout), 0), 0),
isDisplayed()));
passwordInput.perform(replaceText(password));
}
ViewInteraction connectButton = onView(
allOf(withId(R.id.connect_button),
withText(R.string.button_connect),
childAtPosition(childAtPosition(withId(R.id.login_layout), 3), 1),
isDisplayed()));
connectButton.perform(click());
sleep(1000);
AtomicBoolean basicAuthRequired = new AtomicBoolean(false);
onView(withText(R.string.dialog_basic_auth_title)).withFailureHandler((throwable, matcher) -> basicAuthRequired.set(true))
.check(doesNotExist());
if (basicAuthRequired.get()) {
onView(allOf(withId(R.id.dialog_basic_auth_username), isDisplayed()))
.perform(replaceText(testRes.getString(io.homeassistant.android.test.R.string.test_basic_auth_user)));
onView(allOf(withId(R.id.dialog_basic_auth_password), isDisplayed()))
.perform(replaceText(testRes.getString(io.homeassistant.android.test.R.string.test_basic_auth_password)));
onView(allOf(withId(android.R.id.button1), withText(R.string.dialog_basic_auth_button_login), isDisplayed()))
.perform(click());
sleep(1000);
}
// Assert service states
HassService service = activity.service;
assertFalse(service.connecting.get());
assertTrue(service.connected.get());
assertEquals(service.authenticationState.get(), HassService.AUTH_STATE_AUTHENTICATED);
// Recreate and re-assert that still connected
Handler handler = new Handler(activity.getMainLooper());
handler.post(activity::recreate);
sleep(20);
assertFalse(service.connecting.get());
assertTrue(service.connected.get());
assertEquals(service.authenticationState.get(), HassService.AUTH_STATE_AUTHENTICATED);
// Logout
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
ViewInteraction logoutButton = onView(allOf(withId(R.id.title), withText(R.string.menu_logout), isDisplayed()));
logoutButton.perform(click());
sleep(200);
onView(withId(R.id.login_layout)).check(ViewAssertions.matches(isDisplayed()));
assertFalse(service.connecting.get());
assertFalse(service.connected.get());
assertEquals(service.authenticationState.get(), HassService.AUTH_STATE_NOT_AUTHENTICATED);
}
@Test
public void testFeatureTemplate() throws Throwable {
MainActivity activity = activityRule.getActivity();
FeatureFragment fragment = new FeatureFragment();
fragment.toastManager = Mockito.mock(ToastManager.class);
fragment.presenter = new FeatureFragmentPresenter();
FeatureManager featureManager = Mockito.mock(FeatureManager.class);
fragment.presenter.featureManager = featureManager;
Mockito.when(featureManager.loadData()).thenReturn(Observable.error(new Exception("error")));
activity.getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_content_container, fragment)
.commit();
Espresso.onView(ViewMatchers.withId(R.id.feature_loader))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
Mockito.verify(fragment.toastManager, VerificationModeFactory.times(1)).makeToast(Mockito.any(), Mockito.eq("error"), Mockito.any(), Mockito.anyInt());
ArrayList<FeatureModel> models = new ArrayList<>();
models.add(new FeatureModel());
models.add(new FeatureModel());
models.add(new FeatureModel());
Mockito.when(featureManager.loadData()).thenReturn(Observable.fromIterable(models).delay(3, TimeUnit.SECONDS));
Mockito.when(fragment.toastManager.makeToast(Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyInt()))
.thenThrow(new IllegalStateException("Error should not apprend"));
Espresso.onView(ViewMatchers.withId(R.id.feature_retry))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)))
.perform(ViewActions.click())
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
Espresso.onView(ViewMatchers.withId(R.id.feature_loader))
.check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
Espresso.onView(ViewMatchers.withId(R.id.feature_rv))
.perform(RecyclerViewActions.actionOnItemAtPosition(2, ViewActions.click()));
Mockito.clearInvocations(featureManager);
Mockito.verify(featureManager, VerificationModeFactory.noMoreInteractions()).loadData();
activityRule.runOnUiThread(fragment::reload);
Espresso.onIdle();
}
public void checkRootChildIs(Class<? extends View> clazz) {
root().check(ViewAssertions.matches(ViewMatchers.hasDescendant(ViewMatchers.isAssignableFrom(clazz))));
}
@Test
public void assertHiddenToolbarIsNotVisible() {
mainPage.hiddenToolbar().check(ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)));
}
@Test
public void assertToolbarIsVisible() {
mainPage.toolbar().check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}
public void testStartActivityTestStringExtra2WithExtras() throws Exception {
Espresso.onView(ViewMatchers.withText(R.string.test_parcelable_extras)).perform(ViewActions.click());
Espresso.onView(ViewMatchers.withText("Giang")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
Espresso.onView(ViewMatchers.withText("26")).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
}