I am a bit confused about `TestCoroutineContext`. ...
# coroutines
a
I am a bit confused about
TestCoroutineContext
. In unit testing, should I init it in classes that have
CoroutineContext
in the constructor?
s
Implement your unit-test as a CoroutineScope and assign (add / +) the (Supervisor)Job of your test and the TestCoroutineContext of your test to the overridden 'coroutineContext'
Then call 'this.testCoroutineContext.triggerActions()' ('this' is your test class instance) when needed, etc
Copy code
class MyTestSuite : CoroutineScope {
    private val job = SupervisorJob()
    private val testCoroutineContext = TestCoroutineContext()
    
    override val coroutineContext = job + testCoroutineContext

    @ AfterEach
    fun tearDown() { job.cancel() }
    
    @ Test
    fun myTest() {
        ...
        ...
        launch {
            val result = myCodeUnderTest()
            assertThat(result, `is`(expectedValue))
        }
       ...
        testCoroutineContext.triggerActions()
        ... 
        testCoroutineContext.advanceTimeBy(500L)
        ...
    }
    ...
}
a
Thank you @streetsofboston, I’ll try that.