如何单元测试 Android ConnectivityManager
How to unit test Android ConnectivityManager
我正在构建一个应用程序,通过它我们可以使用 ConnectivityManager
class 检测互联网连接的可用性,但我不确定如何使用 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
}
}
您可以使用 Roboelectric 来测试您的 ConnectivityMgr
class。设备连接到 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
用于获取和更新传输。
我正在构建一个应用程序,通过它我们可以使用 ConnectivityManager
class 检测互联网连接的可用性,但我不确定如何使用 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
}
}
您可以使用 Roboelectric 来测试您的 ConnectivityMgr
class。设备连接到 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
用于获取和更新传输。