Can something like “Rule” be used in kotest? I nee...
# kotest
l
Can something like “Rule” be used in kotest? I need to set the MainCoroutineRule.
s
junit rule ?
l
YES
s
no, they're for junit, but you might not need it. What does main coroutine rule do ?
l
Copy code
@ExperimentalCoroutinesApi
class MainCoroutineRule(
    val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {

    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(testDispatcher)
    }

    override fun finished(description: Description?) {
        super.finished(description)
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }
}
I am trying to apply kotest to Android.
s
In kotest, all tests are coroutines, so you can just use withContext and set any dispatcher you want
Copy code
test("my test") {
  withContext(TestCoroutineDispatcher()) {
    ...
  }
}
or if that doesn't work (I'm not sure what Dispatchers.setMain is), you could write a listener to do that easily
Copy code
class MainCoroutineListener(
    val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestListener() {

    override fun beforeTest(description: Description?) {
        Dispatchers.setMain(testDispatcher)
    }

    override fun afterTest(description: Description?) {
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }
}
l
Is this how to create a new testListener?
Is it possible to create a custom listener?
Oh I see.
class MyTestClass : FunSpec({ listeners(TimerListener) // tests here })
class MyTestClass : FunSpec({ listeners(MainCoroutineListener) // tests here })
s
yes
exactly
or if you want to register them at the global level, you can use project config
l
Thank you. You are really kind.
l
Thank you. It was very helpful.
👍🏻 1