How to check internet connection enabled or disabled in Espresso for Android

Issue

In my application have a button that will be enabled or disabled based on internet connection so how can I write Espresso code for checking internet connection in Android?

Solution

Probably the same as usually.

You will need appropriate Context for getting ConnectivityManager. If you are using ActivityTestRule in your Espresso tests, then just pass:

mActivityTestRule.getActivity()

to the method, that checks connection status.

Sample code:

public static boolean isConnected(Context context) {
    ConnectivityManager connectivityManager
             (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo  connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo ! null && activeNetworkInfo.isConnected();
}

Usage:

assertTrue(isConnected(mActivityTestRule.getActivity()));

Answered By РR. Zagórski

Leave a Comment