ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Faking Network Responses with MockK (Featuring Ktor)

Ioannis Anifantakis
ProAndroidDev
Published in
9 min readJan 21, 2025

--

Introduction

When you’re building an Android app — or even a cross-platform Kotlin Multiplatform (KMM) project — that relies on network calls, things can get slow and unreliable if you’re always calling a real server — especially during testing.

By combining MockK, Koin, and Ktor, you can “fake” your network responses, so your tests and development stay smooth and reliable — even when offline.

Note: Although we use Ktor in this article (because it’s Kotlin-friendly and perfect for KMM), the MockK + Koin approach easily applies to any networking library — such as OkHttp, Retrofit, or others. As long as you wrap your network calls in an interface (like ApiService), you can swap in a mock or a real implementation as needed.

Enter MockK

MockK is a Kotlin-first mocking library that offers:

  • Native Kotlin support: Ideal for projects using coroutines or advanced Kotlin features.
  • Clear syntax: every { ... } returns ... to define how mocks respond, and verify/coVerify to confirm calls.
  • Flexible options: Like “relaxed” mocks to reduce boilerplate, and coVerify for suspend functions.

Because MockK is pure Kotlin, it often feels more natural than Java-oriented libraries — especially on modern Android and KMM projects.

Why Ktor?

Ktor is a Kotlin-native framework for building and consuming HTTP APIs. It works on the JVM, Android, iOS (via Kotlin/Native), and more. In Android apps, you might use it as your HTTP client, but in KMM projects, you can share this network logic across multiple platforms:

  1. Pure Kotlin: Suits KMM perfectly — no platform-specific bridging for networking.
  2. Lightweight & Composable: Configure pipeline features like logging, JSON parsing, and timeouts.
  3. Multiplatform: Same code for Android, iOS, desktop, or server-based projects.

When using MockK to fake Ktor responses, you effectively short-circuit real network requests, returning data as if Ktor had made the call — without hitting an actual server. This synergy is what makes your tests fast, reliable, and…

--

--

Responses (2)

Write a response