在Android Instrumented测试中模拟无Internet连接/ Internet连接缓慢

问题描述

我正在编写一个库,用于连续检查android设备的连接,并在设备连接,断开连接或互联网连接变慢时提供回调。

https://github.com/muddassir235/connection_checker

我想为此库编写Android Instrumented测试,并且我需要模拟没有互联网连接以及互联网连接速度慢的情况。

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-设置返回true的calculateIsFailure()的呼叫百分比。 在测试中,您可以调用setErrorPercentage(100)以确保将发生网络错误。默认情况下,引发错误的时间为延迟的0到3倍。