Espresso test to check the max length in an editText

Espresso is a testing framework in android, which is used to test the UI elements in android like editText, textView, button, recyclerView and so on. One thing to note here is that Espresso synchronises all UI events. In case if we want to check network operations, we have to use IdlingResource, which I will explain in my upcoming tutorials.

Here I am verifying the mobile number (editText) can enter max 13 characters. I created a custom matcher, checkMaxLength which will check the max length of editText is 13 characters. We can pass any integer value as we wish.


import android.os.Build;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.text.InputFilter;
import android.view.View;
import android.widget.TextView;

import com.smartandroidians.myloci.activities.LoginActivity;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;


/**
 * Created by Androidians on 18/10/17.
 */

@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {

    @Rule
    public ActivityTestRule activityTestRule = new ActivityTestRule(LoginActivity.class);

    @Test
    public void verifyMobileNumber() {
        SystemClock.sleep(2000);

        onView(withId(R.id.et_mobile_number))
            .perform(typeText("+919912345678"), closeSoftKeyboard())
                .check(matches(checkMaxLength(13)));
    }

    public static TypeSafeMatcher checkMaxLength(final int lines) {
        return new TypeSafeMatcher() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            protected boolean matchesSafely(View item) {
                InputFilter[] filters = ((TextView) item).getFilters();
                InputFilter.LengthFilter lengthFilter =(InputFilter.LengthFilter) filters[0];

                return lengthFilter.getMax() == lines;
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("checkMaxLength");
            }
        };
    }
}


Comments

Popular posts from this blog

Open Gallery and get the selected image in appplication

AlarmManager and Notification in Android

Dismiss or Cancel dialog by swipe gesture