Jenya Kyrmyza
Jenya Kyrmyza

Reputation: 327

espresso testing used in fragment

I've never used espresso before. Now i want to auto type some text in editText field fragment. I know only how to do it with Activity.

@LargeTest
public class EspressoTest {


    @Rule
    public ActivityTestRule<CheckInActivity> mActivityRule =
            new ActivityTestRule<>(CheckInActivity.class);
    @Test
    public void testActivityShouldHaveText() throws InterruptedException {
        onView(withId(R.id.editText)).perform(clearText(), typeText("KI"));
    }
}

I have MainFragment hosted by MainActivity and editText is placed inside MainFragment layout.

Also is there a way in espresso to click on some text, so it could find the view by text?

Upvotes: 0

Views: 1749

Answers (3)

piotrek1543
piotrek1543

Reputation: 19361

Also is there a way in espresso to click on some text, so it could find the view by text?

To catch a view by its text you can do as in this example:

onView(withString(R.string.editText)).check(matches(isDisplayed()));

To catch a text or just a part of it, you can use (I think it's possible also in Robotium) Hamcrest matchers. Here you would find propably all matchers: Hamcrest 1.3 Quick Reference

To make it more clear, I would give you some examples:

onView(withId(R.id.textView)).check(matches(withText(startsWith("Hello"))));

onView(withId(R.id.action_bar_main)).check(matches(withText(String.valueOf(contains("Hello")))));

onView(withId(R.id.textView)).check(matches(withText(endsWith("Hello"))));

I think this would be also useful:

How do I detect a view that I have created programmatically in espresso

Upvotes: 2

user1240878
user1240878

Reputation:

If you want to find the view by text, you can use onView(withText()).

However, you may need to chain a couple of matchers to find exactly what you want. allOf() lets you do just this. You may also need to click into your text field before you can type.

onView(allOf(
    withId(R.id.editText),
    withText(R.string.edit_text)
)).perform(click(),
           clearText(),
           typeText("KI")
   );

I prefer to use replaceText() on most tests to save time.

Upvotes: 1

Jenya Kyrmyza
Jenya Kyrmyza

Reputation: 327

For now i decided to use robotium because yet i don't know how to implement it using espresso Robotium has such methods as waitForFragment and waitForActivity

Upvotes: 1

Related Questions