Search code examples
androidkotlinkotlin-coroutineskoin

Testing ViewModel in Android with Koin and Kotlin coroutines


I started using Koin and I need to test a ViewModel that asks the Repository to retrieve a file from the internal storage of the phone.

When I'm setting the ViewModel test up, I'm doing:

@Before
    fun setup() {
        startKoin {
            modules(dataModule)
        }
        declareMock<Repository> {
            fakeAccount = moshiAccountAdapter.fromJson(json)
            whenever(this.getAccount()).thenReturn(fakeAccount)
        }
    }

but the repository getAccount method is suspend fun getAccount(): Account?, so I'm getting an error in the ViewModelTest class saying suspend function getAccount should be called only from a coroutine or from another suspending function.

Thanks in advance!


Solution

  • You can make use of runBlocking { } block to run suspended functions for test purposes