Skip to content

Instantly share code, notes, and snippets.

@OptIn(ExperimentalCoroutinesApi::class)
class NeverEndingCoroutineTest {
@Test
fun `should emit error when playSound throws`() = runTest {
val exception = Exception("Oopsie")
val soundPlayer = mockk<SoundPlayer>()
coEvery { soundPlayer.playSound() } throws exception
@Test
fun `should increase the playback counter after the sound has finished playing`() = runTest {
val soundPlayer = mockk<SoundPlayer>()
coEvery { soundPlayer.playSound() } coAnswers { delay(1000) }
val sut = MediaPlayer(this, soundPlayer)
sut.play()
advanceTimeBy(1000)
@Test
fun `should not increase the playback counter until the sound has finished playing`() = runTest {
val soundPlayer = mockk<SoundPlayer>()
coEvery { soundPlayer.playSound() } coAnswers { delay(1000) }
val sut = MediaPlayer(this, soundPlayer)
sut.play()
advanceTimeBy(500)
interface SoundPlayer {
suspend fun playSound()
}
class MediaPlayer(
private val scope: CoroutineScope,
private val soundPlayer: SoundPlayer
) {
var playbackCounter = 0
@Test
fun `should change state to Playing after play() called`() = runTest(UnconfinedTestDispatcher()) {
val soundPlayer = mockk<SoundPlayer>()
coJustRun { soundPlayer.playSound() }
val sut = MediaPlayer(this, soundPlayer)
sut.playerState.test {
awaitItem() shouldBe PlayerState.Stopped
interface SoundPlayer {
suspend fun playSound()
}
sealed class PlayerState {
object Stopped : PlayerState()
object Playing : PlayerState()
}
class MediaPlayer(
class MediaPlayer(...) {
...
fun dispose() {
scope.cancel()
}
}
interface IssueReporter {
fun reportIssue(e: Exception)
}
interface SoundPlayer {
suspend fun playSound()
}
class MediaPlayer(
private val scope: CoroutineScope,
interface SoundPlayer {
suspend fun playSound()
}
class MediaPlayer(
private val scope: CoroutineScope,
private val soundPlayer: SoundPlayer
) {
val playerErrors = MutableSharedFlow<Exception>()
class ListAdapter(val itemClickListener : () -> Unit) { ...