片段中使用的浓缩咖啡测试

espresso testing used in fragment

我以前从未用过浓缩咖啡。现在我想在 editText 字段片段中自动键入一些文本。我只知道如何使用 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"));
    }
}

我有 MainFragment 托管的 MainActivity 并且 editText 放置在 MainFragment 布局中。

在 espresso 中有没有一种方法可以点击一些文本,这样它就可以通过文本找到视图?

现在我决定使用 robotium,因为我还不知道如何使用 espresso 来实现它 Robotium 有 waitForFragment 和 waitForActivity

等方法

如果你想通过文本查找视图,你可以使用onView(withText())

但是,您可能需要链接几个匹配器才能准确找到您想要的内容。 allOf() 让你做到这一点。您可能还需要在输入之前单击进入您的文本字段。

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

我更喜欢在大多数测试中使用 replaceText() 以节省时间。

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

要通过文本捕捉视图,您可以按照此示例进行操作:

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

要捕捉文本或只是其中的一部分,您可以使用(我认为在 Robotium 中也可以)Hamcrest 匹配器。在这里您可能会找到所有匹配器:Hamcrest 1.3 Quick Reference

为了更清楚,我举几个例子:

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"))));

我认为这也很有用: