Skip to content

Instantly share code, notes, and snippets.

@xavierlepretre
Created November 14, 2015 17:03
Show Gist options
  • Save xavierlepretre/d2f9637638b993625ebf to your computer and use it in GitHub Desktop.
Save xavierlepretre/d2f9637638b993625ebf to your computer and use it in GitHub Desktop.
"Assume Android is connected". Runs the individual test if the Android device is connected to the network, in an Espresso test environment.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.test.InstrumentationRegistry;
import org.junit.Assume;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class IsConnectedTestRule implements TestRule
{
@Override public Statement apply(final Statement base, Description description)
{
return new Statement()
{
@Override public void evaluate() throws Throwable
{
ConnectivityManager cm = (ConnectivityManager) InstrumentationRegistry
.getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
Assume.assumeTrue(activeNetwork != null &&
activeNetwork.isConnectedOrConnecting());
base.evaluate();
}
};
}
}
@xavierlepretre
Copy link
Author

You need to add in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment