Hey folks, Question about kotlin coroutines testin...
# coroutines
s
Hey folks, Question about kotlin coroutines testing api in 1.6.0 when i should use
Copy code
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
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
Copy code
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.
Copy code
@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
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
You could do that, or just get the dispatcher from the test scope given by
runTest
🙏 1
👍 1
s
thanks, will keep in mind