https://kotlinlang.org logo
#koin
Title
# koin
k

KotlinLeaner

02/23/2023, 2:11 PM
Hi guys, I am injecting Dispacters.IO in m project. Like this
Copy code
val dispatcherModule = module {
    // Dispatchers
    single(named(DISPATCHER_IO)) {
        <http://Dispatchers.IO|Dispatchers.IO>
    }
}

// some other place to use startKoin
startKoin { modules(
                listOf(dispatcherModule)) }
Copy code
class PairViewModelTest {

    @get:Rule
    val testInstantTaskExecutorRule: TestRule = TestMainCoroutineRule()

    @get:Rule
    val koinTestRule = KoinTestRule.create {
        modules(dispatcherModule)
    }

    @MockK private lateinit var mockCoroutineDispatcher: CoroutineDispatcher

    private val subject by lazy { spyk(PairViewModelTest(mockCoroutineDispatcher))}

    @Before
    fun setUp() {
        MockKAnnotations.init(this, relaxed = true)
        loadKoinModules(module {
            factory {
                mockCoroutineDispatcher
            }
        })
    }
   /// more test here which is failed
}
my all tests are failed
So what is wrong in here?
Copy code
class java.lang.Object cannot be cast to class java.lang.Boolean (java.lang.Object and java.lang.Boolean are in module java.base of loader 'bootstrap')
java.lang.ClassCastException: class java.lang.Object cannot be cast to class java.lang.Boolean (java.lang.Object and java.lang.Boolean are in module java.base of loader 'bootstrap')
@arnaud.giuliani any suggestion for this?
a

abbic

02/23/2023, 2:47 PM
I think the problem is that, to test a class that uses coroutines, you need to pass a real dispatcher. try looking at this
I personally dont see the need to use Koin at all in a test like this, but i havent worked with koin closely enough to make that claim strongly
k

KotlinLeaner

02/23/2023, 2:53 PM
Thanks for sharing the above document. The document which you shared is very complicated. I think there is a better way of doing it in koin.
a

abbic

02/23/2023, 3:51 PM
i think that document is about as straightforward as it gets about testing coroutines...
certainly you cant mock the dispatcher
k

KotlinLeaner

02/23/2023, 5:59 PM
Yeah I get it now. Thanks for great guidance. It works with above document.