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.

2
  • stackoverflow.com/questions/36173947/… Commented May 8, 2019 at 23:45
  • i'm also facing the same problem.. I wasn't sure if mocking the private object was possible with mockk.? Commented Jul 2, 2019 at 5:54

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.