0Pricing
Kotlin Multiplatform Academy · Lezione

Simulare il client e i repository Ktor

Utilizzi MockEngine e fake per test deterministici.

Simulare il client e i repository Ktor è una lezione Kotlin Multiplatform Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Kotlin Multiplatform Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Kotlin Multiplatform Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Tests Should Not Hit the Network

Real HTTP calls are slow and flaky in tests. Instead you fake the response so each run is fast and deterministic. 🎯

Ktor Ships a MockEngine

Ktor includes a built-in MockEngine that returns canned responses instead of making real requests.

Build a Mock Client

Construct an HttpClient on top of MockEngine and decide exactly what bytes and status it replies with.

val client = HttpClient(MockEngine) {
    engine { addHandler { respondOk("[]") } }
}

Return Custom JSON

Inside the handler, call respond with the JSON body and headers your code expects to parse.

respond(
    content = "{\"name\":\"Sam\"}",
    headers = headersOf(HttpHeaders.ContentType, "application/json")
)

Simulate Errors

Have the handler reply with a status like 500 to verify your error handling without a real server.

respond("oops", HttpStatusCode.InternalServerError)

Inject the Client

Your repository should accept its HttpClient as a parameter, so tests pass the mock and production passes the real one.

class UserRepo(private val client: HttpClient)

Why a Fake Repository

To test a ViewModel you do not even need Ktor: pass a fake repository that returns fixed data.

Fake an Interface

Because your repo hides behind an interface, a fake is just a small class implementing it with canned results.

class FakeRepo : UserRepo {
    override suspend fun load(id: Int) = User("Sam")
}

Control Failure Paths

A fake can also throw on demand, letting you test how callers react to a failing data layer.

override suspend fun load(id: Int): User =
    throw IOException("offline")

Fakes vs Mocks

A hand-written fake is simple and multiplatform-safe, while mocking libraries often lack full Kotlin/Native support.

Deterministic by Design

With MockEngine and fakes, every test controls its inputs, so results never depend on a network or shared state. ✅

Quick Check

Pick the right way to fake HTTP.

Recap

Swap real HTTP for MockEngine and inject fake repositories so tests stay fast, isolated, and predictable.

Domande Frequenti

La lezione «Simulare il client e i repository Ktor» è gratuita?

Sì — il testo completo di «Simulare il client e i repository Ktor» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Kotlin Multiplatform Academy, passa a CoddyKit PRO. Il corso Kotlin Multiplatform Academy include 4 lezioni in totale.

Cosa imparerò in «Simulare il client e i repository Ktor»?

Utilizzi MockEngine e fake per test deterministici. Eserciti Kotlin Multiplatform Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Kotlin Multiplatform Academy?

Non è richiesta alcuna esperienza precedente. Kotlin Multiplatform Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Simulare il client e i repository Ktor»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Kotlin Multiplatform Academy?

Sì. Ogni lezione Kotlin Multiplatform Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. kotlin.test in commonTest
  2. Testare funzioni suspend e Flow
  3. Simulare il client e i repository Ktor
  4. Eseguire i test sui target Android e iOS
← Torna a Kotlin Multiplatform Academy