# Testing

> Canonical URL: https://docs.mountaya.com/en/sdks/kotlin/testing/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Test Kotlin code that uses Mountaya offline: answer requests with an HttpExchange, retry on virtual time, script the map and navigation, build errors.

Every part of the SDK that reaches the outside world can be replaced in a test: the HTTP exchange, the clock, the map's renderer and the navigation.

## Test code that calls the API

Every attempt leaves through an `HttpExchange`. Answer it yourself:

```kotlin
import com.mountaya.client.Credential
import com.mountaya.client.ExchangeBody
import com.mountaya.client.ExchangeRequest
import com.mountaya.client.ExchangeResponse
import com.mountaya.client.HttpExchange
import com.mountaya.client.Mountaya
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertTrue

class ActivitiesTest {
    @Test
    fun listsNoActivity() =
        runTest {
            val answered =
                object : HttpExchange {
                    override suspend fun send(request: ExchangeRequest): ExchangeResponse =
                        ExchangeResponse(200, body = ExchangeBody("""{"data": []}""".encodeToByteArray()))
                }
            val mountaya = Mountaya(Credential.Publishable("pk_your_publishable_key"), exchange = answered)
            assertTrue(mountaya.studio.activities.getActivities().data.isEmpty())
        }
}
```

- `HttpExchange.send(ExchangeRequest): ExchangeResponse` is the one way out of the client. `ExchangeRequest` carries `method`, `url`, `headers` and `body`, and `header(name)` reads one in any letter case; it prints its method and address alone, never the credential's headers. `ExchangeResponse(status, headers, body)`, where `ExchangeBody` is a `ByteArray`, a `ReceiveChannel<ByteArray>` read in chunks, or a reading function.
- `SystemExchange()` is the platform's: Ktor over OkHttp on the jvm and Android, over URLSession on iOS. It keeps no cookie, follows no redirect and times nothing out of its own. Wrap it to watch an app's traffic, since the client records nothing.
- Every rule of the client runs over your exchange as over the platform's: retries, idempotency keys, the error ladder. A test of a retry answers `503` first.
- `random = RandomSource` pins every jitter and every drawn idempotency key (`unitDraw()`, `cryptographicUuid()`).

## Control time

Hand the client the test's dispatcher, and every wait and retry runs on virtual time:

```kotlin
import com.mountaya.client.Credential
import com.mountaya.client.ExchangeBody
import com.mountaya.client.ExchangeRequest
import com.mountaya.client.ExchangeResponse
import com.mountaya.client.HttpExchange
import com.mountaya.client.Mountaya
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals

class RetryTest {
    @Test
    fun retriesAfterAnOutage() =
        runTest {
            var attempts = 0
            val flaky =
                object : HttpExchange {
                    override suspend fun send(request: ExchangeRequest): ExchangeResponse {
                        attempts += 1
                        return if (attempts == 1) ExchangeResponse(503) else ExchangeResponse(200, body = ExchangeBody("""{"data": []}""".encodeToByteArray()))
                    }
                }
            // The test's dispatcher: the backoff between the 503 and the 200 waits on virtual time.
            val mountaya =
                Mountaya(
                    Credential.Publishable("pk_your_publishable_key"),
                    exchange = flaky,
                    dispatcher = StandardTestDispatcher(testScheduler),
                )
            mountaya.studio.activities.getActivities()
            assertEquals(2, attempts)
        }
}
```

- Every wait and every budget runs on the caller's coroutine time, so a test under `runTest` spends none once it passes `StandardTestDispatcher(testScheduler)` as `dispatcher`: the answer is then read on virtual time too. A read left on `Dispatchers.Default` would let virtual time run on and spend the attempt's budget before the answer arrived.
- `clock = Clock` states the wall clock a `Retry-After` date and a token's expiry are read on.
- `SessionTokenEngine` runs in the scope you give it: under `runTest`, give it `backgroundScope` and its refreshes run on virtual time.
- `ReplayLocationSource(scope, metersPerSecond, interval, timeSource = testScheduler.timeSource)` walks a route on virtual time; `constructWebhookEvent(…, now = …)` pins the clock a signature is judged by.
- The layers panel's slider reads `LocalMountayaClock`, which a Compose test provides.

## Script the map

`ScriptedMapSurface` stands in for the renderer: it records each camera move and plays clicks, hovers and failed requests:

```kotlin
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya
import com.mountaya.elements.CameraTarget
import com.mountaya.elements.MapEngine
import com.mountaya.elements.ScriptedMapSurface
import kotlin.test.Test
import kotlin.test.assertTrue

class MapTest {
    @Test
    fun movesAreRecorded() {
        val map = MapEngine(Mountaya(Credential.Publishable("pk_your_publishable_key")))
        val surface = ScriptedMapSurface(map, canvas = listOf(390.0, 844.0))
        map.ease(CameraTarget(center = listOf(6.8712, 45.9231), zoom = 12.0))
        // A click at a point of the view and a place, told to the map's events as MapView tells it.
        surface.click(listOf(120.0, 80.0), listOf(6.8712, 45.9231))
        assertTrue(surface.moves.isNotEmpty())
    }
}
```

- `ScriptedMapSurface(map, canvas, zoomLimits)` draws a map nowhere and answers what a renderer would. It records `moves` (each `target` and `motion`), `frames` (each fit's `bounds` and `fit`), `queries` and `relabelled`; it holds `rendered` (the `QueriedFeature`s a point query answers), `liveLayers`, `heldSources`, `baseSources`, `baseLabels` and `projection`, which a test sets.
- It plays `click`, `longClick`, `hover` and `leave` at a point and a place, `failRequest(url, status, source)`, `failStyle()`, `loadTile(source)`, `loadStyle()` and `drawFrame()`, each told to `map.events()` as `MapView`'s renderer tells it.
- It runs on every target, so a map's tests run on the jvm with no emulator. `MapView` itself is tested on a device.

## Script navigation

`ScriptedNavigationEngine` is the navigation in your tests: you answer each route request and hand each position:

```kotlin
import com.mountaya.geo.NavigationRoute
import com.mountaya.geo.NavigationStatus
import com.mountaya.geo.ScriptedNavigationEngine
import kotlin.test.Test
import kotlin.test.assertEquals

class NavigationTest {
    @Test
    fun arrivesAtArgentiere() {
        val line = listOf(listOf(6.8712, 45.9231), listOf(6.9271, 45.9822))
        val navigation = ScriptedNavigationEngine<String>()
        navigation.start("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
        navigation.sent[0].answer(NavigationRoute(line = line, duration = 5_400.0))
        navigation.setPosition(line.last())
        assertEquals(NavigationStatus.Arrived, navigation.state.value.status)
        navigation.close()
    }
}
```

- `ScriptedNavigationEngine<T>()` is a `NavigationEngine<T>` in `mountaya-geo`, on every target. `sent` lists each route request made (`start`, `reroute`), a `ScriptedRouteRequest<T>` the test settles with `answer(route)` or `fail(throwable)`.
- It reports exactly what `RouteFollowingEngine` and `DeviceNavigationEngine` report for the same positions: the same status, progress and arrival, a traveller off the route past 50 m.
- Code written against `NavigationEngine<T>` takes either engine, so the app's screen is tested with the scripted one and runs with the device's.

## Build errors

Every exception has a public constructor, so a test builds the failure its code handles:

```kotlin
import com.mountaya.client.ErrorEntry
import com.mountaya.client.MountayaException
import com.mountaya.client.NotFoundException
import com.mountaya.client.generated.ApiErrorCode
import kotlin.test.Test
import kotlin.test.assertEquals

class ErrorScreenTest {
    // Your app's own words for a failure.
    private fun messageFor(failure: MountayaException): String =
        when (failure) {
            is NotFoundException -> "This itinerary is gone."
            else -> "Something went wrong."
        }

    @Test
    fun aMissingItineraryReadsAsGone() {
        val failure = NotFoundException(errors = listOf(ErrorEntry("Gone.", code = ApiErrorCode.NotFound)), requestId = "req_test")
        assertEquals("This itinerary is gone.", messageFor(failure))
    }
}
```

- Every class of the ladder is built through its public constructor (`NotFoundException()`, `ConflictException(errors = …)`, `ConnectionException(cause = …)`, `ConfigurationException(message)`), each with `errors`, `metadata`, `retryAfter`, `rateLimit`, `requestId` and `cause` as it carries them.
- `ApiException.of(status, …)` answers the class a status maps to, for a double that answers as the API would.
- An exchange answering the status itself is the other way: the client then raises the class, its message and its retries exactly as in production.

## Next steps

- [Troubleshooting](https://docs.mountaya.com/en/sdks/kotlin/troubleshooting.md): The errors developers hit first.
- [API by capability](https://docs.mountaya.com/en/sdks/kotlin/reference/api.md): Every public name of the SDK.
