I have a method to check if my mobile has a connection
ic static boolean thereIsConnection(Context context) {
if(context == null) return false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
return true;
}
}
}
and I have wrote this test but I don't know why the expected output is false:
@Test
public void thereIsConnection() {
Context context = new MockContext();
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities networkCapabilities = manager.getNetworkCapabilities(manager.getActiveNetwork());
Mockito.when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn(manager);
Mockito.when(manager.getNetworkCapabilities(manager.getActiveNetwork())).thenReturn(networkCapabilities);
Mockito.when(networkCapabilities.hasCapability(NetworkCapabilities.TRANSPORT_CELLULAR)).thenReturn(true);
Mockito.when(networkCapabilities.hasCapability(NetworkCapabilities.TRANSPORT_WIFI)).thenReturn(true);
Mockito.when(networkCapabilities.hasCapability(NetworkCapabilities.TRANSPORT_ETHERNET)).thenReturn(true);
Assert.assertThat(Utils.thereIsConnection(context), CoreMatchers.is(true));
Mockito.verify(networkCapabilities).hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
Mockito.verify(networkCapabilities).hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
Mockito.verify(networkCapabilities).hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
}
I have an java.lang.UnsupportedOperationException at android.test.mock.MockContext.getSystemService(MockContext.java:616)
so my question is: how to mock Connectivity Manager?
Aucun commentaire:
Enregistrer un commentaire