0

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")));
Allen Hair
  • 1,021
  • 2
  • 10
  • 21
Roshan Chhetri
  • 149
  • 2
  • 9

2 Answers2

2

I think you should check for this HamcrestMatchers and regexp (Regular Expressions).

According to first one there are many String matchers like startsWith(charSequence), endsWith(charSequence), contains(charSequence) which works perfectly with Espresso.

Check: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

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

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

As an example: textView.check(matches(withText(endsWith("133"))));

but as you're using random numbers, the most interesting matcher would be matchesPattern().

Use regular expressions to check if your string contains proper Fixed part with number at the end.

Here's an example how to deal with it: Regex: Check if string contains at least one digit

As an example:

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

Try also to simplify code to:

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

Hope it will help.

Community
  • 1
  • 1
piotrek1543
  • 19,130
  • 7
  • 81
  • 94
0

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

}
RosAng
  • 1,010
  • 2
  • 18
  • 42