KOTLIN · 비동기
코루틴 테스트 (Coroutine Testing)
runTest와 TestDispatcher로 코루틴 코드를 결정적으로 테스트합니다.
비동기고급testingrunTesttestDispatchercoroutine-test
핵심 설명
runTest와 TestDispatcher로 코루틴 코드를 결정적으로 테스트합니다.
Kotlin code
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
class DataRepository {
suspend fun fetchData(): String {
delay(5000) // 실제 네트워크 지연
return "서버 데이터"
}
}
class DataViewModel(private val repo: DataRepository) {
var data: String = ""
private set
var isLoading: Boolean = false
private set
suspend fun loadData() {
isLoading = true
data = repo.fetchData()
isLoading = false
}
}
// 테스트 코드
fun main() = runTest {
val repo = DataRepository()
val viewModel = DataViewModel(repo)
// runTest는 delay를 자동으로 건너뜀
val job = launch { viewModel.loadData() }
// advanceUntilIdle: 모든 코루틴 완료까지 진행
advanceUntilIdle()
println("데이터: ${viewModel.data}")
println("로딩: ${viewModel.isLoading}")
// delay(5000)이 즉시 실행됨!
println("테스트 시간: ${currentTime}ms")
}학습 팁
runTest는 가상 시간을 사용하므로 delay(5000)이 실제로 5초를 기다리지 않습니다. 테스트가 즉시 완료됩니다.
주의할 점
runBlocking으로 코루틴을 테스트하면 실제 지연이 발생합니다. 코루틴 테스트에는 항상 runTest를 사용하세요.
자주 묻는 질문
코루틴 테스트 (Coroutine Testing)란 무엇인가요?
runTest 와 TestDispatcher 로 코루틴 코드를 결정적으로 테스트합니다.
코루틴 테스트 (Coroutine Testing) 학습 시 주의할 점은 무엇인가요?
runBlocking 으로 코루틴을 테스트하면 실제 지연이 발생합니다. 코루틴 테스트에는 항상 runTest 를 사용하세요.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.