Roshan Chhetri Roshan Chhetri - 2 months ago 30
Android Question

Asserting a random number with Android Espresso automation

I want to assert if a string exists using Espresso.

The String Contains a Fixed part and a random number eg: FR#133, were the 133 is a random number. How can I assert it?


  • It can be any digit number

  • If number is not present the test should fail



I tried the below code that performs a fixed string FR#133 check.

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

Answer

Espresso + UIAutomator helps solving a lot of problems which Espresso alone wont.

My sample Function that Creates a UiObject and assert the text in it.

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

}