androidunit-testingjunitmockitoandroid-connectivitymanager

How to unit test Android ConnectivityManager


I am building an application by which we can detect the availability of internet connection using ConnectivityManager class but I am not sure how to add unit test for this using Mockito. Please help me writing the unit test case for the following code:

class ConnectivityMgr @Inject constructor(val context: Context) {
    fun isConnectedOrConnecting(): Boolean {
        val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            connMgr.getNetworkCapabilities(connMgr.activeNetwork)?.run {
                return hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || hasTransport(
                    NetworkCapabilities.TRANSPORT_CELLULAR
                )
            }
        } else {
            @Suppress("DEPRECATION")
            connMgr.activeNetworkInfo?.let {
                return when (it.type) {
                    ConnectivityManager.TYPE_WIFI -> true
                    ConnectivityManager.TYPE_MOBILE -> true
                    else -> false
                }
            }
        }
        return false
    }
}

Solution

  • You can use Roboelectric to test your ConnectivityMgr class. A sample test when the device is connected to WiFi would be like this:

    fun `should be connected when connected to WiFi`() {
        val connectivityManager = getApplicationContext<Context>().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    
        val networkCapabilities = ShadowNetworkCapabilities.newInstance()
        shadowOf(networkCapabilities).addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        shadowOf(connectivityManager).setNetworkCapabilities(connectivityManager.activeNetwork, networkCapabilities)
    
        assertTrue(connectivityMgr.isConnectedOrConnecting())
    }
    

    Roboelectric provides ShadowNetworkCapabilities for fetching and updating transport.