android - 在 Android Instrumented 测试中模拟无 Internet 连接/慢速 Internet 连接

标签 android kotlin testing connection instrumented-test

我正在编写一个库,它不断检查 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-mock模块,它提供了一个 MockRestAdapter 类,其目的是模拟网络延迟和错误。
这是一个与普通 RestAdapter 一起使用来创建你的服务的实例。您可以在 repo 的 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()返回真。
在您的测试中,您可以调用setErrorPercentage(100)以保证会发生网络错误。默认情况下,抛出错误的时间是延迟的 0 到 3 倍。

关于android - 在 Android Instrumented 测试中模拟无 Internet 连接/慢速 Internet 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63642560/

相关文章:

android - 可以删除 build.gradle (app) 上的一些行

android - 导入按钮是否从解析仪表板数据浏览器中删除了?

java - GregorianCalendar 给出错误的天数

performance - 如何验证我的 LoadRunner 测试脚本是否确实在执行?

Android - 如何发送崩溃报告?

android - onActivityResult() 启用蓝牙和发现后的错误结果代码

android - 如何更改 alertdialog 上肯定按钮的颜色?

android - androidx.collection.ArrayMap和android.util.ArrayMap有什么区别?

wpf - 哪种工具或框架可用于并行运行 WPF 自动化测试?

testing - 在测试之前和之后做一些事情