使用 Android Espresso 自动化断言一个随机数

Asserting a random number with Android Espresso automation

我想使用 Espresso 断言字符串是否存在。

字符串包含固定部分和随机数,例如:FR#133,其中 133 是随机数。我怎么能断言呢?

我尝试了以下执行固定字符串 FR#133 检查的代码。

ViewInteraction textView = onView(
            allOf(withText("FR#133"),
                    childAtPosition(
                            allOf(withId(R.id.toolbar_farmdetail),
                                    childAtPosition(
                                            IsInstanceOf.<View>instanceOf(android.widget.LinearLayout.class),
                                            0)),
                            1),
                    isDisplayed()));
    textView.check(matches(withText("FR#133")));

我认为你应该检查这个 HamcrestMatchersregexp(正则表达式)。

根据第一个,有许多字符串匹配器,如 startsWith(charSequence)endsWith(charSequence)contains(charSequence),它们与 Espresso.

完美配合

检查:http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

示例:http://www.leveluplunch.com/java/examples/hamcrest-text-matchers-junit-testing/

教程:http://qathread.blogspot.com/2014/01/discovering-espresso-for-android.html

举个例子:textView.check(matches(withText(endsWith("133"))));

但是当您使用随机数时,最有趣的匹配器是 matchesPattern()

使用正则表达式检查您的字符串是否包含以数字结尾的正确固定部分。

这是一个如何处理它的例子:Regex: Check if string contains at least one digit

举个例子:

textView.check(matches(withText(matchesPattern("FR#133"))));

也尝试将代码简化为:

textView.check(matchesPattern("FR#133"));

希望对您有所帮助。

Espresso + UIAutomator 帮助解决了很多 Espresso 单独解决不了的问题。

创建 UiObject 并断言其中文本的示例函数。

public static boolean testNumberIDExists(String startString, UiDevice mDevice)
{
    String text="";
    UiObject uio=  mDevice.findObject(new UiSelector().textStartsWith(startString));
    try {
        text= uio.getText();
    } catch (UiObjectNotFoundException e) {
        e.printStackTrace();
        return false;
    }

    return Character.isDigit(text.charAt(text.length()-1));

}