# Mockzilla — Full Documentation > A compile-safe solution for running and configuring a local HTTP server for your mobile apps. Supports Android, iOS, Kotlin Multiplatform and Flutter. Mockzilla is a compile-safe mock HTTP server that runs embedded inside your mobile app during development and testing, letting you mock API responses without a real backend. It targets Android, iOS, Kotlin Multiplatform, Flutter and browser (JS/MSW) apps. Install coordinates: - Kotlin / Android / Kotlin Multiplatform (Maven Central): `com.apadmi:mockzilla` (plus `com.apadmi:mockzilla-common` for the shared models/DSL, and `com.apadmi:mockzilla-mobile-ui` for the embeddable in-app overlay). - Flutter (pub.dev): `mockzilla`. - Native iOS: `SwiftMockzilla` via Swift Package Manager (`https://github.com/Apadmi-Engineering/SwiftMockzilla.git`) or CocoaPods. Important notes for code generation: - There is NO standalone npm / JavaScript package. Do not use `npm install mockzilla`. Browser support (JS, backed by Mock Service Worker) is only reachable through the Flutter `mockzilla_web` plugin or the Kotlin/JS `com.apadmi:mockzilla` target. - Mockzilla is a development and testing tool only. It must never be shipped to production. # Quick Start !!! warning Mockzilla is **not** a production tool. It is for development and testing only. It should **never** be deployed to production. Running a server on device may introduce unforeseen security issues. ## Installation === "KMP & Android" Add the gradle dependency: ```kotlin implementation("com.apadmi:mockzilla:4.0.0") ``` === "iOS" Add the SPM dependency in XCode: 1. File > Swift Packages > Add Package Dependency 2. Add `https://github.com/Apadmi-Engineering/SwiftMockzilla.git` !!! note This is not for KMP projects (for those, the gradle dependency should be added to `shared` source set). This SPM dependency is for purely native iOS apps only. === "Flutter" Either install the package using: ```shell flutter pub add mockzilla ``` Or add the dependency in your pubspec.yaml file directly: ```yaml mockzilla: ``` ## Enable local plaintext traffic !!! important Mockzilla does not support HTTPS, all traffic is cleartext HTTP. === "Android" Add both `localhost` and `127.0.0.1` to your [network_security_config.xml](https://developer.android.com/privacy-and-security/security-config). (We recommend having a separate config for production which does not have these overrides) ```xml # In res/xml/network_security_config.xml localhost 127.0.0.1 # In your AndroidManifest.xml file NSAppTransportSecurity NSAllowsLocalNetworking ``` ## Starting the Server Mockzilla is entirely driven by a config object which is used to start the server. ### (1): Create the config: === "Kotlin" ```kotlin val config = MockzillaConfig.Builder() .addEndpoint( EndpointConfiguration .Builder("Hello World") .setPatternMatcher { uri.endsWith("/greeting") } .setDefaultHandler { MockzillaHttpResponse(body = "Hello World") } ).build() ``` === "Swift" ```swift let config = MockzillaConfigBuilder() .addEndpoint(endpoint: EndpointConfigurationBuilder(id: "Hello world") .setSwiftPatternMatcher { $0.uri.hasSuffix("/greeting") } .setDefaultHandler { _ in MockzillaHttpResponse(body: "Hello world") }.build() ).build() ``` === "Flutter" ```dart final mockzillaConfig = MockzillaConfig().addEndpoint( () => EndpointConfig( name: "Hello world", endpointMatcher: (request) => request.uri.endsWith("/greeting"), defaultHandler: (request) => const MockzillaHttpResponse( body: "Hello world", ), errorHandler: (request) => const MockzillaHttpResponse( statusCode: 418, ), ), ); ``` See [here](endpoints.md) for more information on configuring your endpoints. (Including compile-time safety!) ### (2): Just start the server! !!! note For KMP apps, even though all the configuration can be defined in Kotlin. The server should still be started directly from within native code on both platforms. See the [KMP demo](https://github.com/Apadmi-Engineering/Mockzilla/tree/develop/samples/demo-kmm) for an example. === "Android Application" ```kotlin class RootApplication : Application() { override fun onCreate() { super.onCreate() val config = MockzillaConfig.Builder().... startMockzilla(config, this) } } ``` === "iOS App Delegate" ```swift import UIKit import SwiftMockzilla import mockzilla @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let config = MockzillaConfigBuilder()... startMockzilla(config: config) return true } } ``` === "Flutter" ```dart // Make sure to call this before starting Mockzilla! WidgetsFlutterBinding.ensureInitialized(); await Mockzilla.startMockzilla(mockzillaConfig); ``` ### (3): Call the server from your client code Mockzilla listens for calls to `http://localhost:8080/local-mock` (this should be your base url). To configure the port see [here](/dokka/mockzilla-common/com.apadmi.mockzilla.lib.models/-mockzilla-config/-builder/#581853299%2FFunctions%2F1121797123). It's recommended to choose a different port for each of your apps to prevent clashes. ## Recommendation Since Mockzilla shouldn't be included in production binaries, we recommend creating a new product flavour specifically for the mock and only including this dependency for this variant. === "KMP" For KMP projects this will require creating a new KMP module in your project specifically for the mock. === "Flutter" Flutter itself doesn't support product flavours in the same way as Android or iOS, however we can use different Dart entrypoints into your application and Dart's tree-shaking to achieve a similar effect. 1. Before integrating Mockzilla, duplicate your `main.dart` file and rename it to create `main_mock.dart`. ``` |-lib |-main.dart |-main_mock.dart ``` 2. In `main_mock.dart`, follow the instructions above to configure and start the Mockzilla server and perform any additional configuration on your HTTP client to use the `localhost` base URL above. 3. We can now use the newly created `main_mock.dart` as a different entrypoint to your Flutter app to enable Mockzilla while leaving the standard `main.dart` as your production entrypoint! ```shell flutter run -t lib/main_mock.dart ``` 4. Optionally, feel free to move the Mockzilla config to an auxiliary file. Just make sure that the declarations aren't used in your production app. !!! note Looking for the Web/JS target? See the dedicated [Web guide](web.md) instead - its setup differs enough (a required service worker file, no cleartext-traffic step) to warrant its own walkthrough. ## Tips Ensure your development machine and test device are on the same Wi-Fi network. You can replace `localhost` with your device's IP address and try calling these endpoints from Postman (or a similar REST client.) ![alt text](img/postman-example.png "Postman example") --- # Configuring Endpoints ## Simple Example === "Kotlin" ```kotlin val endpoint = EndpointConfiguration.Builder("Hello World") .setDefaultHandler { MockzillaHttpResponse( statusCode = HttpStatusCode.OK, headers = mapOf("test-header" to "test-value"), body = "{}" ) } .setPatternMatcher { uri.endsWith("greeting") } .build() ``` === "Swift" ```swift let endpoint = EndpointConfigurationBuilder(id: "Hello world") .setDefaultHandler { _ in MockzillaHttpResponse( statusCode: HttpStatusCode.OK, headers: ["test-header": "test-value"], body: "{}" ) }.setSwiftPatternMatcher { $0.uri.hasSuffix("greeting") }.build() ``` === "Flutter" ```dart final endpoint = EndpointConfig( name: "Greeting", endpointMatcher: (request) => request.uri.endsWith("greeting"), defaultHandler: (request) => const MockzillaHttpResponse( headers: {"key": "value"}, body: "Hello world", ), errorHandler: (request) => const MockzillaHttpResponse(statusCode: 500), ); ``` We can then call this endpoint as follows: ```bash SHELL % curl -v http://localhost:8080/local-mock/greeting * Trying 127.0.0.1:8080... * Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0) > GET /local-mock/greeting HTTP/1.1 > Host: 127.0.0.1:8080 > User-Agent: curl/7.87.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Connection: close < Content-Length: 12 < Content-Type: text/plain; charset=UTF-8 < Hello world * Closing connection 0 ``` (This assumes your app is running on a simulator and accessible on localhost; replace `localhost` with your device IP if running on device.) ## Compile-time Safety This relies on a simple concept: **Use the same set of model classes for deserialisation and for your mocks!** Example: === "Kotlin" ```kotlin .setDefaultHandler { MockzillaHttpResponse( body = Json.encodeToString(MyDtoResponseClass("my value")) ) } ``` === "Flutter" It is recommended to use a JSON serialisation library such as [freezed](https://pub.dev/packages/freezed) or [json_serializable](https://pub.dev/packages/json_serializable) that can generate `toJson()`/`fromJson()` methods for you. ```dart MockzillaHttpResponse( body: jsonEncode( FetchDeparturesResponse( departures: [ Departure( arrival: DateTime.now().add(const Duration(minutes: 2)), destination: "East Didsbury", tramType: TramType.single, ) ], ), ), ); ``` ### (1) - Pattern matchers The pattern matching block is how Mockzilla maps an incoming network request to a given endpoint. Given the request data, return `true` if the given endpoint should map to this endpoint. Request data is accessible as follows: === "Kotlin" ```kotlin EndpointConfiguration.Builder("Hello world") .setPatternMatcher { // this: MockzillaHttpRequest } ``` === "Swift" ```swift EndpointConfigurationBuilder(id: "Hello world") .setSwiftPatternMatcher { // $0: MockzillaHttpRequest } ``` === "Flutter" ```dart EndpointConfig( name: "Hello world", endpointMatcher: (request) => request.method == HttpMethod.get && request.uri.endsWith("/departures"), /* Handlers */ ) ``` Where `MockzillaHttpRequest` is defined as follows. ```kotlin data class MockzillaHttpRequest( val uri: String, val headers: Map, val body: String = "", val method: HttpMethod, ) ``` ### (2) - Artificial Latency The following can be configured globally across all endpoints [here](/dokka/mockzilla-common/com.apadmi.mockzilla.lib.models/-mockzilla-config/-builder/#1935914297%2FFunctions%2F1121797123). Network requests generally don't complete instantly. Mockzilla can mimic the latency of a network and can be configured either across all endpoints on the top-level config, or on individual endpoints as follows: === "Kotlin" ```kotlin EndpointConfiguration.Builder("Hello world") .setDelayMillis(100) ``` === "Swift" ```swift EndpointConfigurationBuilder(id: "Hello world") .setDelayMillis(delay: 100) ``` === "Flutter" ```dart EndpointConfig( name: "Fetch departures", endpointMatcher: (request) => request.uri.endsWith("/departures"), defaultHandler: (request) => MockzillaHttpResponse( body: jsonEncode(const FetchDeparturesResponse(departures: []))), errorHandler: (request) => const MockzillaHttpResponse(statusCode: 418), delay: const Duration(milliseconds: 500), ) ``` By default there is no artificial delay. ### (3) - Artificial Errors Mockzilla supports artificially causing network requests to fail. === "Kotlin" ```kotlin EndpointConfiguration.Builder("Hello world") // Optional error handler, called when endpoint is set to fail // Defaults to an empty 400 response. .setErrorHandler { MockzillaHttpResponse(statusCode = HttpStatusCode.NotFound) } .setShouldFail(true) ``` === "Swift" ```swift EndpointConfigurationBuilder(id: "Hello world") // Optional error handler, called when endpoint is set to fail // Defaults to an empty 400 response. .setSwiftErrorHandler { _ in MockzillaHttpResponse(status: HttpStatusCode.NotFound) } .setShouldFail(shouldFail: true) ``` === "Flutter" ```dart EndpointConfig( name: "Fetch departures", endpointMatcher: (request) => request.uri.endsWith("/departures"), defaultHandler: (request) => MockzillaHttpResponse( body: jsonEncode(const FetchDeparturesResponse(departures: []))), // Optional error handler, called when endpoint is set to fail // Defaults to an empty 400 response. errorHandler: (request) => const MockzillaHttpResponse(statusCode: 400), shouldFail: true, ) ``` **The default is for requests to succeed**. !!! note Controlling artificial latency in code is time consuming and inflexible. We recommend using the [Mockzilla Desktop](desktop/overview.md) app or [Embedded Mobile Ui](mobile_ui.md) to do this on the fly. ## Mock Request Lifecycle When calling the Mockzilla server from your app's code the following happens: ```mermaid sequenceDiagram participant A as Client App participant S as Mockzilla Server A->>S: Network request S->>S: Lookup Endpoint based on pattern matchers (1) S->>S: Delay as long as appropriate (2) S->>S: Decide whether to simulate a failure (3) alt Call should succeed S->>S: Check for property overrides from desktop app / embedded UI (4) alt All properties overridden S->>A: Return response using overridden values only (defaultHandler skipped) else Partial override S->>S: Call `defaultHandler` S->>A: Return response, overridden properties take priority over defaultHandler's else No overrides S->>A: Return response by calling block defined by `setDefaultHandler` end else Call should fail S->>A: Return response by calling block defined by `setErrorHandler` end ``` --- # Web / JavaScript !!! warning Web support is newer and less battle-tested than the other platforms - expect some rough edges, and treat the API as subject to change. **It is *not* designed to be consumed from a JavaScript web application, only from Kotlin & Flutter apps running against the web target.** ## How it works Unlike the other platforms, Mockzilla on web isn't a real HTTP server - a browser can't bind a listening port. Instead it's built on [Mock Service Worker (MSW)](https://mswjs.io/), which intercepts `fetch`/`XHR` calls made by your page. This has a couple of practical implications: - The `localhost:8080` base URL is kept only for consistency with the other platforms - nothing actually binds to port 8080. It's just the URL prefix MSW matches requests against. - Requests that don't match any configured endpoint are passed straight through to the real network (`onUnhandledRequest` is set to bypass, not to warn or error). ## Installation Installation should be through the Kotlin or Flutter mechanisms as described in the [Quick Start](quick-start.md) guide. ## Required: Add the mock service worker script This step is easy to miss and isn't handled automatically - without it, starting Mockzilla will fail. MSW needs its worker script, `mockServiceWorker.js`, served from your site's root. 1. Get a copy of the script. Either use the one bundled in this repo at `js-scripts/mockServiceWorker.js` (pinned to MSW `2.11.6`, matching the version Mockzilla uses internally), or generate one yourself with the standard MSW CLI: `npx msw init `. 2. Place it so it's served from your site root: === "Kotlin/JS or KMP web" Copy it to `src/webMain/resources/mockServiceWorker.js` (or `src/jsMain/resources/` if you don't have a `webMain` source set). Kotlin's default resource processing copies everything under that folder straight into your build output, next to `index.html`. === "Flutter" Copy it to `web/mockServiceWorker.js` in your Flutter project. Flutter serves everything under `web/` at the site root, so it'll be available at `/mockServiceWorker.js`. ## Differences from mobile/native A few things that work on Android/iOS don't apply (or don't yet exist) on web - to save you filing a bug for expected behaviour: - No network device auto-discovery in the [desktop app](desktop/overview.md) - a browser tab can't be discovered the way a phone on the same Wi-Fi network can. The embedded mobile UI (which runs in the same page as your app) is the way to control mocks on web. - The connected-device metadata shown in the dashboard won't include an app icon. - [Release mode](additional_config.md#release-mode)'s auth-header generation is a no-op stub on web. ## Distribution There is currently no npm package for consuming Mockzilla from a plain JavaScript/TypeScript project outside of Kotlin or Flutter. --- # Additional Configuration Most Mockzilla configuration is relatively self-explanatory with API references available at the following: * [Kotlin](../dokka/mockzilla-common/com.apadmi.mockzilla.lib.models/-mockzilla-config/-builder/index.html) * [Dart](https://pub.dev/documentation/mockzilla/latest/) ## Logging By default, Mockzilla outputs minimal logging. If more is needed to help with debugging, enable it as follows. === "Kotlin" ```kotlin val config = MockzillaConfig.Builder() .setLogLevel(MockzillaConfig.LogLevel.Verbose) ... .build() ``` === "Swift" ```swift let config = MockzillaConfigBuilder() .setLogLevel(level: LogLevel.verbose) ... .build() ``` === "Flutter" ```dart final mockzillaConfig = const MockzillaConfig( logLevel: LogLevel.verbose, ); ``` ## Release Mode !!! note Release mode is only supported for Kotlin & Swift running on Android & iOS targets. By default, the Mockzilla server can be called by anyone on the network via the device's IP address. This is often useful for debugging. If you need to release your mock app to non-developers, we recommend enabling "release mode" which does the following. 1. Introduces rate limiting to the server 2. Enforces rudimentary token authentication on each request (explained below). 3. Only allows connections from `127.0.0.1` (i.e from apps running on the device). === "Kotlin" ```kotlin val config = MockzillaConfig.Builder() .setIsReleaseModeEnabled(true) // Following is optional, the defaults should be fine for most apps .setReleaseModeConfig( MockzillaConfig.ReleaseModeConfig( rateLimit = 60, rateLimitRefillPeriod = 60.seconds, tokenLifeSpan = 0.5.seconds ) ) ``` === "Swift" ```swift let config = MockzillaConfigBuilder() .setIsReleaseModeEnabled(isRelease: true) // Following is optional, the defaults should be fine for most apps .setReleaseModeConfig( releaseConfig: MockzillaConfig.ReleaseModeConfig( rateLimit: 60, rateLimitRefillPeriod: 60_000, // milliseconds tokenLifeSpan: 500 // milliseconds ) ) ``` An additional header now needs to be added to each request. The header **changes per request** and is generated as follows. === "Kotlin" ```kotlin val params = startMockzilla(config, ..) // Generate a new header for each request. val header = params.authHeaderProvider.generateHeader() ``` === "Swift" ```swift let params = startMockzilla(config: config, ..) // Generate a new header for each request. let header = params.authHeaderProvider.generateHeader() ``` !!! warning We still don't recommend releasing to non-developers, even with this mode if at all avoidable. Mockzilla is NOT a production server substitute and should **NOT** be used in production. --- # BrowserStack ## iOS Mockzilla should work out of the box on iOS with BrowserStack. ## Android BrowserStack seems to proxy local traffic by default. In your client app you'll need to bypass any proxy. ### OkHttp Example ```kotlin OkHttpClient.Builder() .proxy(Proxy.NO_PROXY) ``` ### Ktor Example: See demo app example [here](https://github.com/Apadmi-Engineering/Mockzilla/blob/develop/samples/demo-android/src/main/java/com/apadmi/mockzilla/demo/Repository.kt#L52). --- # Snapshot builds !!! warning Snapshot builds are deployed directly from the `develop` branch of [the main repo](https://github.com/Apadmi-Engineering/Mockzilla). They are *not* stable and should *not* be used for anything other than testing and trying out new features. === "Kotlin" To try out the latest development build add the following Maven url to your project. ```kotlin maven { setUrl("https://central.sonatype.com/repository/maven-snapshots/") } ``` The latest snapshot can be found by examining the latest build [here](https://github.com/Apadmi-Engineering/Mockzilla/actions/workflows/action_deploy_binaries.yml). === "Swift" Snapshots are published to the SPM repos on the branch `deployment/snapshot`: - [SwiftMockzilla](https://github.com/Apadmi-Engineering/SwiftMockzilla/commits/deployment/snapshot/) - [SwiftMockzillaMobileUi](https://github.com/Apadmi-Engineering/SwiftMockzillaMobileUi/commits/deployment/snapshot) === "Flutter" Snapshots are published on [pub.dev](https://pub.dev/packages/mockzilla) as [pre-releases](https://dart.dev/tools/pub/publishing#publishing-prereleases). --- # Mockzilla Desktop (beta) Mockzilla Desktop is a companion app that connects to Mockzilla on your device over your local network, letting you override responses, force failures, and adjust latency live - no code changes or rebuilds required.
Download Mockzilla Desktop

macOS · Windows · Linux

!!! important You **must** be using the same Wi-Fi network on your device running Mockzilla and the device running the desktop app. ## Preparation On iOS add the following to your Info.plist. ```xml NSBonjourServices _mockzilla._tcp ``` This allows your device to be automatically detected on the network. ## Connecting a device Your device should be automatically discovered by Mockzilla (you may need to restart the app on your device). Android emulators are also detected automatically, with no extra setup required. ![alt text](img/device_connection.png "Device connection") !!! note If network discovery does not find your device you can manually type in the IP address of your device. (Don't forget the port!) ### Multiple devices You can connect to more than one device at once - each connected device gets its own tab along the top of the window, so you can switch between them without losing your place. Use the "+" tab to connect another device, and close a tab's ✕ to disconnect. ![alt text](img/multiple_devices.png "Multiple devices") ## Editing mock data Once connected, the app allows you to manipulate the latency of responses as well as their content in different ways. ### Apply a Preset A preset is a predefined response defined in code to cater for a given scenario. ### Adjust Latency Latency can be adjusted on the fly to help debug loading states and to simulate slow networks. ### Force an endpoint to fail Forcing an endpoint to fail causes the `errorHandler` in code to be called (defaulting to a 400 error). ## Global Controls To adjust latency on all endpoints or force all endpoints to fail, use the global controls. ## Monitor logs The bottom panel is a live log of every request your device makes through Mockzilla, whether "Force failure" was enabled or not. Each entry shows the request URL, status code, and response time - colour-coded so slow responses and errors stand out - along with a badge showing whether the response was the result of forced failure ("FORCED"). Selecting a log entry opens its full details: request and response headers, and body content. ![alt text](img/monitor_logs.png "Monitor Logs") ## Miscellaneous controls Alongside the device/app info panel you'll find a few utility controls: - **Refresh all** - re-fetches the latest state from the connected device. - **Clear overrides** - same as "Reset all" in Global Controls. - **Presentation mode** - scales the entire UI, handy when demoing on a projector or a shared screen. - **Dark mode** - forces dark theme regardless of your OS setting. ![alt text](img/misc_controls.png "Miscellaneous Controls") ## Known limitations - The desktop app enforces a minimum compatible Mockzilla server version (`2.0.0`) - if the app you're connecting to bundles an older `mockzilla` library, you'll see an "unsupported version" message instead of the dashboard. Update the `mockzilla` dependency in your app to resolve this. - **Linux is not officially supported.** The desktop app is provided as-is on Linux - rendering issues may occur, and this platform doesn't receive the same testing as macOS and Windows. --- # Mockzilla Mobile UI (alpha) !!! warning This plugin is still experimental and may contain bugs! The API is also subject to change Mockzilla provides an embedded UI for your App to control the server at runtime. ## Installation === "KMP & Android" Add the gradle dependency: ```kotlin implementation("com.apadmi:mockzilla-mobile-ui:1.1.0") ``` === "iOS" Add the SPM dependency in XCode: 1. File > Swift Packages > Add Package Dependency 2. Add `https://github.com/Apadmi-Engineering/SwiftMockzillaMobileUi` !!! note This is not for KMP projects (for those, the gradle dependency should be added to `shared` source set). This SPM dependency is for purely native iOS apps only. === "Flutter" Either install the package using: ```shell flutter pub add mockzilla_ui_mobile ``` Or add the dependency in your pubspec.yaml file directly: ```yaml mockzilla_ui_mobile: 1.1.0 ``` ## Setup If you've not configured the Mockzilla server yet, then do that first [here](quick-start.md)! ### Launch the Embedded UI You can do this from a button click or any trigger in your app code. === "Kotlin" ```kotlin import com.apadmi.mockzilla.mobile.ui.launchManagementUi /// Android Target /// launchManagementUi(context /* Activity Context */) /// iOS Target /// launchManagementUi() // Or // Handle the ViewController directly createManagementUiViewController(onClose = { // Dismiss the ViewController } ``` === "Swift" ```swift import SwiftMockzillaMobileUi launchManagementUiSwift() // Or // Handle the ViewController directly createManagementUiViewControllerSwift { // Dismiss the ViewController } ``` === "Flutter" ```dart import 'package:mockzilla_ui_mobile/mockzilla_ui_mobile.dart'; MockzillaUiMobile.launchManagementUi(); ``` !!! note On web, you can optionally call `MockzillaUiMobile.preloadAssets()` early (e.g. at app start) to speed up the first time the overlay is launched. === "Web" ```kotlin import com.apadmi.mockzilla.launchManagementUi launchManagementUi(rootId = "mockzilla-ui-root") ``` If no element with the given `rootId` exists on the page, one is created automatically as a fixed, bottom-anchored panel. If you'd rather control placement and sizing yourself, add an element with a matching `id` to your page first - it'll be reused as-is. This will launch the UI overlay, allowing a user to configure the mocked endpoints. --- # Presets Mockzilla responses can be changed and configured at runtime either using our [desktop app](desktop/overview.md) or our [embedded UI](mobile_ui.md) that can be included in your app. ## What are presets? Presets are pre-defined responses configured in code that can be applied at runtime. ## Defining presets Presets are applied to individual endpoints, they can be successful responses, errors, or anything else! They're defined in code and show up in the UI as one-tap options - select one and it's applied immediately. You can also create a **custom preset** on the fly, without editing code, using the built-in editor: ![alt text](img/custom_preset.png "Monitor Logs") ### How preset overrides combine with your default handler This is worth understanding precisely, since it's not obvious from the UI: **a preset only overrides the specific fields you set on it.** Status code, headers, and body are each overridden independently - if you leave one unset (for example, you only override the status code), the response for that field still comes from whatever your endpoint's `setDefaultHandler` block returns for that request. The default handler is skipped entirely only once **all three** fields - status, headers, and body - are overridden. Applying a canned preset defined with a full `MockzillaHttpResponse` in code behaves the same way, since it sets all three fields; but a custom preset you build via the "None" body option, for instance, will still fall through to your default handler's body. === "Kotlin" ```kotlin EndpointConfiguration .Builder("Pig") .configureDashboardOverrides { addPreset( name = "George", response = MockzillaHttpResponse( body = Json.encodeToString( AnimalDto( name = "George", age = 2, biography = "George Pig is a fictional character...", ) ) ) ) addPreset( name = "Pig Failure", response = MockzillaHttpResponse(statusCode = HttpStatusCode.NotFound) ) ... ``` === "Swift" ```swift EndpointConfigurationBuilder(id: "Pig") .configureDashboardOverrides { builder in builder.addPreset( response: MockzillaHttpResponse( status: HttpStatusCode.OK, headers: [:], body: AnimalDto( name: "George", age: 2, biography: "George Pig is a fictional character...", ).toJson() ), name: "George", description: nil, type: nil ) } ``` === "Flutter" ```dart EndpointConfig( name: "Pig", ... dashboardOptionsConfig: DashboardOptionsConfig(presets: [ DashboardOverridePreset( name: "George", response: MockzillaHttpResponse( statusCode: 200, headers: {}, body: AnimalDto( name = "George", age = 2, biography = "George Pig is a fictional character...", ).toJsonString(), ) ), DashboardOverridePreset( name: "Pig Failure", response: MockzillaHttpResponse( statusCode: 404, headers: {}, body: "", ) ) ]) ``` ## Applying Presets The presets can be applied through the desktop app or the embedded UI. ## Preset Types

Default Behaviour

By default the preset types are derived from the status code.

Presets
### Overriding This can be helpful if you're simulating an API that doesn't utilise status codes, e.g. using 200 even for errors. === "Kotlin" ```kotlin .configureDashboardOverrides { addPreset( name = "200 Error", response = MockzillaHttpResponse(statusCode = HttpStatusCode.OK), type = DashboardOverridePreset.Type.ServerError ).addPreset( name = "200 Success", response = MockzillaHttpResponse(statusCode = HttpStatusCode.OK), type = DashboardOverridePreset.Type.Success ).addPreset( name = "200 Redirect", response = MockzillaHttpResponse(statusCode = HttpStatusCode.OK), type = DashboardOverridePreset.Type.Redirect ) } ``` === "Swift" ```swift .configureDashboardOverrides { builder in builder.addPreset( name: "200 Error", description: nil, response: MockzillaHttpResponse(status: HttpStatusCode.OK), type: MockzillaDashboardOverridePresetType.servererror ) builder.addPreset( name: "200 Success", description: nil, response: MockzillaHttpResponse(status: HttpStatusCode.OK), type: MockzillaDashboardOverridePresetType.success ) builder.addPreset( name: "200 Redirect", description: nil, response: MockzillaHttpResponse(status: HttpStatusCode.OK), type: MockzillaDashboardOverridePresetType.redirect ) } ``` === "Flutter" ```flutter DashboardOptionsConfig(presets: [ DashboardOverridePreset( name: "200 Error", response: MockzillaHttpResponse(statusCode: 200), description: null, type: DashboardOverridePresetType.serverError ), DashboardOverridePreset( name: "200 Success", response: MockzillaHttpResponse(statusCode: 200), description: null, type: DashboardOverridePresetType.success ), DashboardOverridePreset( name: "200 Redirect", response: MockzillaHttpResponse(statusCode: 200), description: null, type: DashboardOverridePresetType.redirect ), ]) ```