https://kotlinlang.org logo
Title
a

A Gamal

01/17/2019, 4:45 PM
I am a bit confused about
TestCoroutineContext
. In unit testing, should I init it in classes that have
CoroutineContext
in the constructor?
s

streetsofboston

01/17/2019, 5:44 PM
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
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

A Gamal

01/17/2019, 9:01 PM
Thank you @streetsofboston, I’ll try that.