Last active
May 30, 2023 13:01
-
-
Save mkulak/f708c1d100da0dc01bf49d42f57406f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.delay | |
import kotlin.time.Duration.Companion.milliseconds | |
import kotlin.time.Duration.Companion.seconds | |
suspend fun multiplyWithDelay(a: Int, b: Int): Int { | |
delay(10.seconds) | |
return a * b | |
} | |
data class Box(var value: Int) | |
suspend fun modify(box: Box) { | |
box.value = 1 | |
delay(10.milliseconds) | |
box.value = 2 | |
delay(20.milliseconds) | |
box.value = 3 | |
} | |
@OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class) | |
class TimeServiceKtTest { | |
@Test | |
fun `multiply with delay`() = runTest { | |
val time = measureTime { | |
val res = multiplyWithDelay(2, 3) | |
assertEquals(6, res) | |
} | |
println("Test took $time") | |
} | |
@Test | |
fun `modify box`() = runTest { | |
val box = Box(0) | |
launch { | |
modify(box) | |
} | |
Thread.sleep(100) | |
assertEquals(0, box.value) | |
runCurrent() | |
assertEquals(1, box.value) | |
advanceTimeBy(5.milliseconds) | |
runCurrent() | |
assertEquals(1, box.value) | |
advanceTimeBy(5.milliseconds) | |
runCurrent() | |
assertEquals(2, box.value) | |
advanceTimeBy(21.milliseconds) | |
// runCurrent() | |
assertEquals(3, box.value) | |
advanceUntilIdle() | |
assertEquals(3, box.value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment