android - 在 Android Instrumented 测试中模拟无 Internet 连接/慢速 Internet 连接
问题描述
我正在编写一个库,它会持续检查 android 设备的连接,并在设备连接、断开连接或互联网连接变慢时给出回调。
https://github.com/muddassir235/connection_checker
我想为这个库编写 Android Instrumentated 测试,我需要模拟没有互联网连接以及缓慢的互联网连接。
package com.muddassir.connection_checker
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ConnectionCheckerTest {
@Test
fun checkDisconnectedState() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
InstrumentationRegistry.getInstrumentation().runOnMainSync {
val connectionChecker = ConnectionChecker(context, null)
connectionChecker.connectivityListener = object: ConnectivityListener {
override fun onConnected() {
assertTrue(false)
}
override fun onDisconnected() {
assertTrue(true)
}
override fun onConnectionSlow() {
assertTrue(false)
}
}
// Disconnect from the internet. How do I do this?
connectionChecker.startChecking()
}
Thread.sleep(30000)
}
}
解决方案
Retrofit 有一个retrofit-mock
模块,它提供了一个 MockRestAdapter 类,其目的是模拟网络延迟和错误。
这是一个与普通 RestAdapter 一起使用来创建你的服务的实例。您可以在存储库的 samples/mock-github-client/ 文件夹中查看完整示例:https ://github.com/square/retrofit/blob/master/retrofit-mock/src/test/java/retrofit2/mock /MockRetrofitTest.java
MockRestAdapter 提供以下 API:
setDelay
- 设置网络往返延迟,以毫秒为单位。
setVariancePercentage
- 设置网络往返延迟的正负方差百分比。
setErrorPercentage
- 设置calculateIsFailure()
返回 true 的调用百分比。在你的测试中,你可以打电话setErrorPercentage(100)
保证会发生网络错误。默认情况下,抛出错误的时间是延迟的 0 到 3 倍。
推荐阅读
- javascript - Bootstrap 侧边栏 - 固定桌面和设备上的响应式覆盖
- java - 即使错误的 XML 根元素,Jackson 解组成功
- scala - 为什么这个简单的 quill 引用无法编译?
- r - 如何在 Bookdown 中编写伪代码
- c# - System.Net.WebClient 在将 DownloadString 与 Bloomberg Web 服务一起使用时获取 ConnectionReset
- python - 如何循环遍历熊猫数据框并在条件下修改值?
- mendix - 如何在 Mendix 中导入小部件包?
- javascript - 如何让黄瓜在 selenium nightwatch 框架中运行
- r - 如何将函数应用于许多 ML 模型并保存它们的输出?
- c - 如何将 Windows 消息从一个线程传递到另一个线程?