Özet - İleri test
- Kotlin kursu
- İleri seviye
- Ders 48/83
- 5 dk
runTest, Turbine ve MockK'yı birleştirerek bir ViewModel testi yazarsın.
Özet - İleri test
Bu grupta ileri test araçlarını gördün: runTest ile coroutine testi, Turbine ile Flow testi, MockK ile mocklama, Testcontainers ile gerçek konteyner ve kotest-property ile property testi.
Bu ders, üçünü bir araya getiren küçük bir görev içerir: bir fetchUser fonksiyonunu runTest içinde çağırıp sonucunu yazdıran bir test kodu yazacaksın. Bu kalıp, ileri Kotlin testlerinin temelini oluşturur.
Uygulama Özet: fetchUser testini yaz
fetchUser(id: Int): String adında suspend fonksiyon tanımla; id 1 için "Ayşe" döndürsün. main içinde runTest bloğu aç; fetchUser(1) sonucunu bir değişkene ata, assertEquals("Ayşe", result) ile doğrla ve println(result) yazdır.
Başlangıç kodu
import kotlinx.coroutines.test.runTest
// suspend fonksiyon: id=1 için Ayşe döndür
// main'de runTest bloğu aç; fetchUser(1) sonucunu assert ve yazdırÖrnek çözüm
import kotlinx.coroutines.test.runTest
import kotlin.test.assertEquals
suspend fun fetchUser(id: Int): String {
return "Ayşe"
}
fun main() = runTest {
val result = fetchUser(1)
assertEquals("Ayşe", result)
println(result)
}Beklenen çıktı
Ayşe
Soru ve cevaplar
Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.
1 Bir suspend fonksiyonu test ederken hangi builder kullanılır?
- Thread.sleep
- runBlocking
- runTest Doğru cevap
- Thread.start
Açıklama: runTest, suspend fonksiyonlar için TestScope açar.
2 Turbine test bloğunu tamamla
scoreFlow().____ {
println(awaitItem())
awaitComplete()
}
scoreFlow().test {
println(awaitItem())
awaitComplete()
}
Açıklama: scoreFlow().test bir Turbine aboneliği açar.
3 Test araçlarını eşle
| Kavram | Anlamı |
|---|---|
runTest |
Coroutine test |
Turbine |
Flow test |
MockK |
Mocklama |
kotest-property |
Property test |