https://kotlinlang.org logo
Title
l

Luis Daivid

01/21/2021, 5:37 AM
Can something like “Rule” be used in kotest? I need to set the MainCoroutineRule.
s

sam

01/21/2021, 5:38 AM
junit rule ?
l

Luis Daivid

01/21/2021, 5:38 AM
YES
s

sam

01/21/2021, 5:39 AM
no, they're for junit, but you might not need it. What does main coroutine rule do ?
l

Luis Daivid

01/21/2021, 5:39 AM
@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

sam

01/21/2021, 5:40 AM
In kotest, all tests are coroutines, so you can just use withContext and set any dispatcher you want
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
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

Luis Daivid

01/21/2021, 5:43 AM
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

sam

01/21/2021, 5:44 AM
yes
exactly
or if you want to register them at the global level, you can use project config
l

Luis Daivid

01/21/2021, 5:44 AM
Thank you. You are really kind.
l

Luis Daivid

01/21/2021, 5:46 AM
Thank you. It was very helpful.
👍🏻 1