Skip to content

Instantly share code, notes, and snippets.

@davydes
Created August 12, 2021 08:34
Show Gist options
  • Save davydes/951748ac4c755ebd4ed95cf79c10a17d to your computer and use it in GitHub Desktop.
Save davydes/951748ac4c755ebd4ed95cf79c10a17d to your computer and use it in GitHub Desktop.
Coroutine test with mockito.kotlin
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.kotlin.doSuspendableAnswer
import org.mockito.kotlin.mock
import kotlin.coroutines.coroutineContext
interface Subject {
suspend fun myName(): String?
}
class SubjectImpl(private val obj: Subject) : Subject {
override suspend fun myName(): String? = obj.myName()
}
class CoroutineTest {
private val mock = mock<Subject> {
onBlocking { myName() } doSuspendableAnswer {
coroutineContext[CoroutineName]?.name
}
}
private val subj = SubjectImpl(mock)
@Test
fun check() {
val name = "test-coroutine"
val result = runBlocking(CoroutineName(name)) {
subj.myName()
}
assertThat(result).isEqualTo(name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment