1

我正在构建一个应用程序,我们可以通过它使用ConnectivityManager类检测互联网连接的可用性,但我不确定如何使用Mockito. 请帮我编写以下代码的单元测试用例:

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
    }
}
4

1 回答 1

7

您可以使用 Roboelectric 来测试您的ConnectivityMgr课程。设备连接到 WiFi 时的示例测试如下:

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 提供ShadowNetworkCapabilities获取和更新传输。

于 2020-06-06T05:17:07.340 回答