NetworkMockPlugin
Ktor client plugin for intercepting HTTP requests and returning mock responses.
This plugin integrates with the DevView Network Mock module to allow developers to mock API calls during development and testing. It intercepts outgoing HTTP requests and can return predefined mock responses instead of making actual network calls.
Features
Request Interception: Intercepts HTTP requests at the send phase
Selective Mocking: Mock individual endpoints while others use real network
Global Toggle: Master switch to enable/disable all mocking
Path Parameters: Supports path parameters like
/users/{userId}Multiple Hosts: Can mock different hosts (staging, production, etc.)
State Persistence: Mock configuration persists across app restarts
How It Works
Plugin intercepts every HTTP request using Ktor's
HttpSendmechanismChecks if global mocking is enabled via DataStore state
Attempts to match the request (host, path, method) to a configured endpoint
If matched and mock is enabled for that endpoint, loads and returns the mock response
Otherwise, proceeds with the actual network call
Default Installation
When NetworkMock is registered via rememberModules, repositories are resolved automatically from com.worldline.devview.networkmock.core.NetworkMockInitializer:
val client = HttpClient(OkHttp) {
install(NetworkMockPlugin)
}Custom Installation
For testing or advanced scenarios, repositories can be injected explicitly:
val client = HttpClient(OkHttp) {
install(NetworkMockPlugin) {
mockRepository = myMockConfigRepository
stateRepository = myMockStateRepository
}
}Mock File Setup
Create composeResources/files/networkmocks/mocks.json:
{
"apiGroups": [{
"id": "my-backend",
"name": "My Backend",
"endpoints": [{
"id": "getUser",
"name": "Get User Profile",
"path": "/v1/users/{userId}",
"method": "GET"
}],
"environments": [
{ "id": "staging", "name": "Staging", "url": "https://staging.api.example.com" },
{ "id": "production", "name": "Production", "url": "https://api.example.com" }
]
}]
}Add response files following the naming convention:
composeResources/files/networkmocks/responses/my-backend/getUser/
├── getUser-200.json (shared — used by all environments)
└── getUser-404.json
composeResources/files/networkmocks/responses/my-backend/staging/getUser/
└── getUser-200.json (staging-specific — overrides the shared variant)Error Handling
The plugin fails gracefully — if configuration cannot be loaded, a response file is missing, or any exception occurs, it falls back to the actual network and logs the reason.
Thread Safety
The plugin is thread-safe. Multiple requests can be intercepted concurrently without issues. State reads are atomic through DataStore.