https://kotlinlang.org logo
Title
s

samp

04/06/2022, 11:25 PM
Hey folks, Question about kotlin coroutines testing api in 1.6.0 when i should use
val dispatcher = StandardTestDispatcher()
val scope = TestScope(dispatcher)

@Test
fun testFoo() = runTest(dispatcher) {
    // ...
}

vs

val dispatcher = StandardTestDispatcher()
val scope = TestScope(dispatcher)

@Test
fun testFoo() = runTest {
    // ...
}
what if i don’t pass the dispatcher, I know it will default to
StandardTestDispatcher
but wouldn’t be those two different
dispatcher
here? 1. created by runTest 2. created by
dispatcher
property
d

Dmitry Khalanskiy [JB]

04/07/2022, 7:19 AM
In the second case, the dispatchers would have different
TestCoroutineScheduler
instances, and so they can't be used in the same test. However, the first case is also incorrect: if you create a
TestScope
explicitly, you also must use the form
scope.runTest
, like
val dispatcher = StandardTestDispatcher()
val scope = TestScope(dispatcher)

@Test
fun testFoo() = scope.runTest {
  ...
}
otherwise, the scope is not checked for leaked coroutines at the end of the test. Alternatively, just don't create anything.
@Test
fun testFoo() = runTest {
  ...
}
will work just fine. Create a scope if you do need to inject a scope somewhere into the entities that you're testing.
s

samp

04/07/2022, 7:08 PM
thanks for the insights, Thanks for the explanation, So better to not use any custom dispatcher and scope until and unless i need to pass dispatcher or scope to the production class (which we usually do: to inject scope or dispatcher)
@Dmitry Khalanskiy [JB]
Alternatively, just don’t create anything.
```@Test
fun testFoo() = runTest {
...
}```
will work just fine. Create a scope if you do need to inject a scope somewhere into the entities that you’re testing.
what if i need to pass dispatcher to the entities? In that case, do you suggest to create an explicitly create a dispatcher and use that dispatcher to run the test like: runTest(dispatcher) and pass that dispatcher to the entities as well?
j

Joffrey

04/07/2022, 9:46 PM
You could do that, or just get the dispatcher from the test scope given by
runTest
:thank-you: 1
👍 1
s

samp

04/09/2022, 4:08 PM
thanks, will keep in mind