lundi 23 novembre 2015

Handle Espresso exceptions

In my android app I want to test if a text view is displaying a certain text. The fact that the text appear or not depends on a background thread which is loading data from internet; I cannot set the app to not-idle because this process is continuously running and the activity under test has no control over it; so my approach is to begin doing assertions with a timeout limit; something like that:

        boolean success = false;

        long now = System.currentTimeMillis();
        long limit = now + 10000;

        do {

            if (System.currentTimeMillis() >= limit){
                throw new TimeoutAssertionException();
            } else {

                try {

                    onView(ViewMatchers.withId(R.id.customChatButton_countTextView))
                            .check(matches(ViewMatchers.withText(String.valueOf(messageNumber))));

                    success = true;
                } catch (Exception e){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e1) {
                        if (BuildConfig.LOCAL_LOG){
                            Log.w(TAG, "InterruptedException in goToVideowalk(): " +
                            e.getMessage());
                        }
                    }
                }

            }

        } while (!success);

TimeoutAssertionException is a custom exception of mine which implements EspressoException. My guess is that the check() method will throw an exception and the catch block will catch it; but it doesn't happen; the flow never enters into the catch block, logcat outputs the following:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text: is "4"' doesn't match the selected view. Expected: with text: is "4" Got: "TextView{id=2131558643, res-name=customChatButton_countTextView, visibility=INVISIBLE, width=48, height=48, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=81.0, y=21.0, text=, input-type=0, ime-target=false, has-links=false}"

Anyone knows any method to perform a check and handle the error in order to not provoke a test failure?

Aucun commentaire:

Enregistrer un commentaire