1

Is this possible to mock using mockk library.

I have a class (some parts removed, tried to simplify the problem)

class SettingsManager(val application: Application) {

    private val fetcher: Fetcher = Fetcher(application)

    suspend fun fetchRemote() {
        fetcher.doFetch()
    }
}

class Fetcher(val application: Application) {
    fun doFetch() {
        if (canFetch()) {
            // make GET request
        }
    }

    fun canFetch() {
        if (application.isOnline()) {
            return true
        }
        return false
    }
}

Extension


@RequiresPermission(value = Manifest.permission.ACCESS_NETWORK_STATE)
fun Context.isOnline(): Boolean {
    val connectivityManager = this
            .getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
    connectivityManager?.apply {
        val netInfo = activeNetworkInfo
        netInfo?.let {
            if (it.isConnected) return true
        }
    }
    return false
}

I'm trying to basically mock the work that the private class Fetcher does. I thought I could do:

val mockFetcher = mockk<Fetcher>()
every { mockFetcher.canFetch() } returns true

But that does not mock the private instance. Is there a way to mock the private instance? I understand that if I created an interface for the private Fetcher and instead made it public and injected the type, I can mock it. But the logic for fetching doesn't need to be known to the outside consumers of Settings Manager. I wasn't sure if mocking the private object was possible with mockk.

halfer
  • 19,824
  • 17
  • 99
  • 186
Crystal
  • 28,460
  • 62
  • 219
  • 393
  • https://stackoverflow.com/questions/36173947/mockito-mock-private-field-initialization – mbmc May 08 '19 at 23:45
  • i'm also facing the same problem.. I wasn't sure if mocking the private object was possible with mockk.? – thangaraj Jul 02 '19 at 05:54

0 Answers0