下面列出了怎么用android.support.test.espresso.action.ViewActions的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void clickItemShowCollectPage() {
clickNavigationLoginShowLoginScreen();
onView(withId(R.id.login_account_edit))
.perform(ViewActions.typeText("2243963927"));
onView(withId(R.id.login_password_edit))
.perform(ViewActions.typeText("qaz123"),
ViewActions.closeSoftKeyboard());
clickView(R.id.login_btn);
//将异步请求转换为同步执行
IdlingRegistry.getInstance().register(mCountingIdlingResource);
checkVisible(R.id.nav_view);
onView(withId(R.id.nav_view))
.perform(NavigationViewActions.navigateTo(R.id.nav_item_my_collect));
checkVisible(R.id.collect_recycler_view);
}
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));
}
private void makeScreenshots0(Context context, String languageTag, String theme)
{
SuntimesTestConfig configuration = defaultConfig;
if (config.containsKey(languageTag)) {
configuration = config.get(languageTag);
}
configureAppForTesting(context, languageTag, configuration, theme);
activityRule.getActivity().finish();
activityRule.launchActivity(activityRule.getActivity().getIntent());
onView( withId(android.R.id.content)).perform(ViewActions.swipeUp());
long waitTime = 6 * 1000; // wait a moment
IdlingResource waitForResource = new ElapsedTimeIdlingResource(waitTime);
IdlingPolicies.setMasterPolicyTimeout(waitTime * 2, TimeUnit.MILLISECONDS);
IdlingPolicies.setIdlingResourceTimeout(waitTime * 2, TimeUnit.MILLISECONDS);
registerIdlingResources(waitForResource);
captureScreenshot(activityRule.getActivity(), version + "/" + languageTag, "activity-alarms0-" + theme);
unregisterIdlingResources(waitForResource);
}
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 addMetaDetails() {
String passTitle = "PassageTitle";
String passage = "Short Passage.";
String timer = "180";
onView(withId(R.id.button_add_item)).perform(click());
closeSoftKeyboard();
onView(withId(R.id.meta_title)).perform(typeText(passTitle));
closeSoftKeyboard();
onView(withId(R.id.meta_passage)).perform(typeText(passage), ViewActions.closeSoftKeyboard());
sleep();
onView(withId(R.id.meta_timer)).perform(scrollTo());
sleep();
onView(withId(R.id.meta_timer)).perform(click()).perform(typeText(timer), ViewActions.closeSoftKeyboard());
sleep();
onView(withResourceName("buttonDefaultPositive")).perform(click());
}
/**
* After setKeepHint(true) a hint should appeared.
* After setKeepHint(false) a hint should disappear.
*/
@Test
public void setKeepHintTest() {
onView(withId(phone_input))
.perform(new HintViewAction("9997055671"))
.perform(dontKeepHints) // just to be sure
// the first check. After setKeepHint(true) the hint should appear immediate
.perform(ViewActions.typeText("999"))
.perform(keepHints)
.check(matches(withText("+7(999)705-56-71")))
// the second check. After setKeepHint(false) the hint should disappear immediate
.perform(dontKeepHints)
.check(matches(withText("+7(999)")));
}
/** Verifies that states in the history keep their associated view state. */
@Test public void goingBackWorksAndRestoresState() {
// Enter some text in the name field and go forward.
// The field's view state, including the text we entered, should be remembered in the history.
onView(withId(R.id.welcome_screen_name))
.perform(ViewActions.typeText("Bart\n"));
onView(withId(R.id.basic_activity_frame))
.check(matches(hasDescendant(isAssignableFrom(HelloView.class))));
pressBack();
onView(withId(R.id.basic_activity_frame))
.check(matches(hasDescendant(isAssignableFrom(WelcomeView.class))));
// When we navigated back, the view state of the name field should have been restored.
onView(withId(R.id.welcome_screen_name))
.check(matches(withText("Bart")));
}
private long calcTime(boolean weex) {
BenchmarkActivity benchmarkActivity = mActivityRule.getActivity();
benchmarkActivity.loadWeexPage(weex);
if(weex) {
onView(withClassName(Matchers.is(WXFrameLayout.class.getName()))).perform
(ViewActions.swipeDown());
}
else{
onView(withClassName(Matchers.is(TextView.class.getName()))).perform
(ViewActions.swipeDown());
}
return benchmarkActivity.getDuration();
//.getWXInstance().getWXPerformance().screenRenderTime;
}
@Test
public void cleanTaskFlag() {
onView(withText("ClearTask")).perform(ViewActions.click());
//测试是否对应的Intent被发送
intended(allOf(
IntentMatchers.hasAction("hhhh"),
hasComponent(hasShortClassName(".intenttest.IntentTestActivity")),
IntentMatchers.hasFlag(Intent.FLAG_ACTIVITY_CLEAR_TASK)));
}
@Test
public void cleanTopFlag() {
onView(withText("ClearTop")).perform(ViewActions.click());
//测试是否对应的Intent被发送
intended(allOf(
hasComponent(hasShortClassName(".intenttest.IntentTestActivity")),
IntentMatchers.hasFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
@Test
public void clickAppNavigationIconOpenNavigation() {
onView(ViewMatchers.withId(R.id.drawer_layout))
.check(matches(DrawerMatchers.isClosed(Gravity.LEFT)));
onView(withContentDescription(
TestUtils.getToolBarNavigationContentDescription(
mActivityTestRule.getActivity(),
R.id.common_toolbar
))).perform(ViewActions.click());
onView(withId(R.id.drawer_layout))
.check(matches(DrawerMatchers.isOpen(Gravity.LEFT)));
}
@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 onSearchTermEntered_NonMatchingItemsNotShown() {
onView(isAssignableFrom(EditText.class))
.perform(ViewActions.typeText("2"));
onView(withId(R.id.bookRecycler))
.check(adapterItemCountLowerThan(45));
}
@Test
public void assertGoesToRepositoryAfterSuccessfulLogin()
throws Exception {
loginPage.username().perform(ViewActions.typeText("hello"));
assertThat(loginPresenter.username).isEqualTo("hello");
loginPage.password().perform(ViewActions.typeText("world"));
assertThat(loginPresenter.password).isEqualTo("world");
loginPage.loginButton().perform(ViewActions.click());
ConditionWatcher.waitForCondition(new LoginWaitForDialogInstruction(loginPresenter));
mainPage.checkRootChildIs(RepositoriesView.class);
}
/**
* Insert a text into a view.
*
* @param input input string which needs to be typed.
* @param expectedOutput expected output from this input which will be checked.
*/
public static void insertTextAtOnceAndAssert(String input, String expectedOutput) {
// Type input.
onView(withId(android.R.id.primary))
.perform(ViewActions.replaceText(input));
assertExpectedOutput(expectedOutput);
}
@Test
public void inputCityName(){
onView(withId(R.id.etCityName)).perform(typeText(cityName), ViewActions.closeSoftKeyboard());
onView(withId(R.id.btnSearch)).perform(click());
// Check if the add note screen is displayed
onView(withId(R.id.progressBar)).check(matches(not(isDisplayed())));
onView(withId(R.id.tvCityName)).check(matches(withText("Sydney")));
}
/**
* Tests a long press gesture by performing it and then checking if the action is displayed
*/
@Test
public void testLongPress(){
onView(withId(R.id.input_gesture_action_pad)).perform(ViewActions.longClick());
checkIfActionIsDisplayed("Long Press");
}
/**
* Tests a pull to refresh control by pulling to refresh and checking if the
* display matches specific pattern for the time.
*/
@Test
public void testRefresh() {
onView(withId(R.id.input_refresh_scrollview)).perform(ViewActions.swipeDown());
onView(withId(R.id.input_refresh_display)).
check(matches(RegularExpressionMatcher.
matchesPattern("\\d{2}:\\d{2}:\\d{2} (AM|PM)")));
}
public void testDetailActivityOpen () throws InterruptedException {
// Work around, it would be better use Espresso Idling resources
Thread.sleep(1000);
Espresso.onView(withId(R.id.activity_movies_recycler)).perform(
RecyclerViewActions.actionOnItemAtPosition(2, ViewActions.click()));
Espresso.onView(withId(R.id.activity_detail_scroll))
.check(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()));
}
public void editMetaDetails() {
String passTitle = "EditedPassageTitle";
String passage = "EditedShort Passage.";
onView(withId(R.id.template_meta_listview)).perform(longClick());
onView(withId(R.id.action_edit)).perform(click());
closeSoftKeyboard();
onView(withId(R.id.meta_title)).perform(replaceText(passTitle));
closeSoftKeyboard();
onView(withId(R.id.meta_passage)).perform(replaceText(passage), ViewActions.closeSoftKeyboard());
sleep();
onView(withResourceName("buttonDefaultPositive")).perform(click());
}
@Test
public void dontPostWithEmptyTextView() {
FeedController mockFeedController = mock(FeedController.class);
doNothing().when(mockFeedController).sendPostAsync(anyString());
when(mComponent.feedController()).thenReturn(mockFeedController);
getActivity();
onView(withId(R.id.fab)).perform(ViewActions.click());
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(mockFeedController, never()).sendPostAsync(captor.capture());
}
@Test
public void postItem() throws InterruptedException {
FeedController mockFeedController = mock(FeedController.class);
doNothing().when(mockFeedController).sendPostAsync("post text");
when(mComponent.feedController()).thenReturn(mockFeedController);
getActivity();
onView(withId(R.id.inputText))
.perform(ViewActions.click())
.perform(ViewActions.typeText("post text"));
onView(withId(R.id.fab)).perform(ViewActions.click());
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(mockFeedController).sendPostAsync(captor.capture());
assertThat(captor.getValue(), is("post text"));
onView(withId(R.id.inputText)).check(matches(withText("")));
}
@Test
public void selectDir() throws IOException {
ViewInteraction radioButton = onView(
allOf(withId(R.id.radioDir), withText("Select directory"),
withParent(withId(R.id.radioGroup)),
isDisplayed()));
radioButton.perform(click());
onView(withId(R.id.button_ftp)).perform(ViewActions.scrollTo());
ViewInteraction button = onView(
allOf(withId(R.id.button_ftp), isDisplayed()));
button.perform(click());
ViewInteraction recyclerView = onView(
allOf(withId(android.R.id.list), isDisplayed()));
// press pub
recyclerView.perform(actionOnItemAtPosition(1, click()));
ViewInteraction okButton = onView(
allOf(withId(R.id.nnf_button_ok),
withParent(allOf(withId(R.id.nnf_button_container),
withParent(withId(R.id.nnf_buttons_container)))),
isDisplayed()));
// Click ok
okButton.perform(click());
ViewInteraction textView = onView(withId(R.id.text));
textView.check(matches(withText("ftp://anonymous:[email protected]:21/pub")));
}
@Test
public void withSingleClick() throws IOException {
ViewInteraction radioButton = onView(
allOf(withId(R.id.radioNewFile),
withParent(withId(R.id.radioGroup)),
isDisplayed()));
radioButton.perform(click());
ViewInteraction checkBox = onView(
allOf(withId(R.id.checkSingleClick), isDisplayed()));
checkBox.perform(click());
onView(withId(R.id.button_fastscroll)).perform(ViewActions.scrollTo());
ViewInteraction button = onView(
allOf(withId(R.id.button_fastscroll), isDisplayed()));
button.perform(click());
ViewInteraction recyclerView = onView(
allOf(withId(android.R.id.list), isDisplayed()));
// Refresh view (into dir, and out again)
recyclerView.perform(actionOnItemAtPosition(1, click()));
recyclerView.perform(actionOnItemAtPosition(0, click()));
// Navigate to file
recyclerView.perform(actionOnItemAtPosition(1, click()));
recyclerView.perform(actionOnItemAtPosition(2, click()));
// Click file
recyclerView.perform(actionOnItemAtPosition(4, click()));
// Should have returned
ViewInteraction textView = onView(withId(R.id.text));
textView.check(matches(withText("/storage/emulated/0/000000_nonsense-tests/B-dir/file-3.txt")));
}
@Test
public void clickTwiceShouldNotClearFilename() throws IOException {
ViewInteraction radioButton = onView(
allOf(withId(R.id.radioNewFile), withText("Select new file"),
withParent(withId(R.id.radioGroup)),
isDisplayed()));
radioButton.perform(click());
onView(withId(R.id.button_fastscroll)).perform(ViewActions.scrollTo());
ViewInteraction button = onView(
allOf(withId(R.id.button_fastscroll), withText("Pick With Fast Scroller"),
isDisplayed()));
button.perform(click());
ViewInteraction recyclerView = onView(
allOf(withId(android.R.id.list), isDisplayed()));
// Refresh view (into dir, and out again)
recyclerView.perform(actionOnItemAtPosition(1, click()));
recyclerView.perform(actionOnItemAtPosition(0, click()));
// Navigate to file
recyclerView.perform(actionOnItemAtPosition(1, click()));
recyclerView.perform(actionOnItemAtPosition(2, click()));
// Click on file once
recyclerView.perform(actionOnItemAtPosition(4, click()));
// Filename should be entered in field
ViewInteraction editText = onView(withId(R.id.nnf_text_filename));
editText.check(matches(withText("file-3.txt")));
// Click twice
recyclerView.perform(actionOnItemAtPosition(4, click()));
// Filename should not change
editText.check(matches(withText("file-3.txt")));
}
/**
* Verifies that the current Flow state is maintained, as well as view state associated with
* Flow state.
*/
@Test public void rotationMaintainsState() {
// Enter some text on the welcome screen
onView(withId(R.id.welcome_screen_name))
.perform(ViewActions.typeText("Bart"));
rotate();
// We should still have that text, despite the configuration change.
onView(withId(R.id.welcome_screen_name))
.check(matches(withText("Bart")));
// Continue to the next screen and verify that it's showing info from our Flow state object.
onView(withId(R.id.welcome_screen_name))
.perform(ViewActions.typeText("\n"));
onView(withId(R.id.hello_name))
.check(matches(withText("Hello Bart")));
// Change the text in the counter TextView. Only this view knows its state, we don't store it
// anywhere else.
onView(withId(R.id.hello_increment))
.perform(click())
.perform(click());
onView(withId(R.id.hello_counter))
.check(matches(withText("2")));
rotate();
// Verify that we still have our Flow state object.
onView(withId(R.id.hello_name))
.check(matches(withText("Hello Bart")));
// Verify that the counter TextView's view state was restored.
onView(withId(R.id.hello_counter))
.check(matches(withText("2")));
}
@Test
public void ViewActions() {
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button)).perform(ViewActions.click());
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button)).perform(ViewActions.typeText("HaHa"), ViewActions.click());
Espresso.onView(ViewMatchers.withId(json.chao.com.wanandroid.R.id.button)).perform(ViewActions.scrollTo(), ViewActions.click());
}