vendredi 28 août 2020

Simulate No Internet Connection/Slow Internet Connection in Android Instrumentation Test

I am writing a library that checks the the connection of the android device continuously and gives a callback when the device gets connected, disconnected or the internet connection becomes slow.

https://github.com/muddassir235/connection_checker

I want to write Android Instrumentation tests for this library and I need to simulate no internet connection as well as a slow internet connection.

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

Aucun commentaire:

Enregistrer un commentaire