Koin: declareMock not working with mockk (android)

Created on 28 Jun 2020  路  1Comment  路  Source: InsertKoinIO/koin

Problem

trying to mock a repository class using declareMock and mockk but it doesn't seem to be working as i am getting the data from the real repository.

Version

implementation "org.koin:koin-androidx-viewmodel:2.1.6"
testImplementation "org.koin:koin-test:2.1.6"

Code

My application class (only relevant parts):

class MyApplication : Application() {
    companion object {
        val appModule = module {
            single<RepositoryUserLists> { RepositoryUserListsImpl() }
        }
    }

    override fun onCreate() {
        super.onCreate()

        startKoin {
            androidLogger()
            androidContext(this@MyApplication)
            modules(appModule)
        }
    }
}

My test class (only relevant parts)

class TestRepositoryUserLists : KoinTest {
    @get:Rule
    val koinTestRule = KoinTestRule.create {
        modules(MyApplication.appModule)
    }

    @get:Rule
    val mockProvider = MockProviderRule.create { clazz ->
        mockkClass(clazz.java.kotlin)
    }

    @Rule
    @JvmField
    val instantExecutorRule = InstantTaskExecutorRule()

    private val repo: RepositoryUserLists by inject()

    @Before
    fun before() {
        declareMock<RepositoryUserLists> {
            every { getAllLists() } returns MutableLiveData(listOf(MyList("test list")))
        }

        //PROBLEM IS HERE
        //Expected: a list containing one item names "test list".
        //Actual: empty list (like in real repository).
        repo.getAllLists().value 
    }
}

Am i doing something wrong?

question

Most helpful comment

Your mock provider should be like follow with Mockk:

@get:Rule
val mockProvider = MockProviderRule.create { clazz ->
    mockkClass(clazz)
}

There is a typo in the official doc

>All comments

Your mock provider should be like follow with Mockk:

@get:Rule
val mockProvider = MockProviderRule.create { clazz ->
    mockkClass(clazz)
}

There is a typo in the official doc

Was this page helpful?
0 / 5 - 0 ratings