Utils { public static boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return (cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isConnectedOrConnecting(); }  static void openUrl(String url, Context context); static boolean isOnline(Context context);  }
@Test public void testShouldReturnFalseIfNetworkDisconnected() throws Exception { ConnectivityManager connectivityManager = mock(ConnectivityManager.class); when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager); when(connectivityManager.getActiveNetworkInfo()).thenReturn(null); boolean online = Utils.isOnline(context); assertThat(online, is(false)); }
@Test public void testShouldReturnTrueIfNetworkConnected() throws Exception { ConnectivityManager connectivityManager = mock(ConnectivityManager.class); when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(connectivityManager); NetworkInfo networkInfo = mock(NetworkInfo.class); when(connectivityManager.getActiveNetworkInfo()).thenReturn(networkInfo); when(networkInfo.isConnectedOrConnecting()).thenReturn(true); boolean online = Utils.isOnline(context); assertThat(online, is(true)); }