Httpmocker
HttpMocker is a simple HTTP mocking library written in Kotlin to quickly and easily handle offline modes in your apps
Install / Use
/learn @speekha/HttpmockerREADME
HttpMocker
HttpMocker is a very lightweight Kotlin library that allows to mock HTTP calls relying on either OkHttp or the Ktor client libraries.
-
It can be used for unit or integration tests: by providing predefined responses and instead of actual calls to servers, you're avoiding the risk of unpredictable results due to network failure or server errors.
-
It can also be used to implement an offline mode in your application for debugging or demo purposes: you can prepare complete scenarios that will let users explore your app's features without the need for an actual connection or account.
Thanks to the MockResponseInterceptor (for OkHttp) or the mockableHttpClient (for Ktor), web service calls will not be dispatched to the network, but responses will be read from static configuration files or computed dynamically instead. The mocker also allows recording scenarios that can be reused later.
Current Version
httpmocker_version = '2.0.0-alpha'
Current version is stable for Android/JVM builds. It still has Alpha status because we would like to add support for iOS. Any help with implemention and deployment for iOS is welcome.
Gradle
Maven Central
For stable versions, check that you have the mavenCentral repository.
// Add Jcenter to your repositories if needed
repositories {
mavenCentral()
}
For Snapshot versions, check that you have Sonatype's snapshot repository.
// Add oss.sonatype.org to your repositories if needed
repositories {
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
}
Dependencies
Adding HttpMocker
This library contains several parts:
- a core module handling the mock logic
- an engine module corresponding to the HTTP library you use (OkHttp or Ktor)
- an additional adapter to parse the scenario files for static mocks
You can add the dependency to your build.gradle by adding on of the following lines:
// Core module: you don't need to add it explicitly to your gradle (it will be included as a transitive dependency
// of the other modules)
implementation "fr.speekha.httpmocker:mocker-core:2.0.0-alpha"
// Handles mocks for OkHttp
implementation "fr.speekha.httpmocker:mocker-okhttp:2.0.0-alpha"
// Handles mocks for KTor
implementation "fr.speekha.httpmocker:mocker-ktor:2.0.0-alpha"
Currently, there are six possible options that are provided for parsing, based on some of the most commonly used serialization libraries and on a custom implementation (no third party dependency):
- Jackson
- Gson
- Moshi
- Kotlinx serialization
- Custom JSON implementation
- Custom Sax-based implementation (uses XML scenarios instead of JSON)
This should allow you to choose one matching what you already use in your application (in order to prevent
duplicate libraries in your classpath, like Jackson and GSON). If you would prefer to use XML instead
of JSON, the SAX-based parser allows you to do it. If you choose one of these options, all you need to add is the
corresponding implementation line in your gradle file:
// Parses JSON scenarios using Jackson
implementation "fr.speekha.httpmocker:jackson-adapter:2.0.0-alpha"
// Parses JSON scenarios using Gson
implementation "fr.speekha.httpmocker:gson-adapter:2.0.0-alpha"
// Parses JSON scenarios using Moshi
implementation "fr.speekha.httpmocker:moshi-adapter:2.0.0-alpha"
// Parses JSON scenarios using Kotlinx Serialization
implementation "fr.speekha.httpmocker:kotlinx-adapter:2.0.0-alpha"
// Parses JSON scenarios using a custom JSON parser
implementation "fr.speekha.httpmocker:custom-adapter:2.0.0-alpha"
// Parses XML scenarios using a custom SAX parser
implementation "fr.speekha.httpmocker:sax-adapter:2.0.0-alpha"
If none of those options suit your needs, you can also provide your own implementation of the Mapper class. You can
also bypass that dependency altogether if you don't plan on using static mocks or the recording mode.
External dependencies
- HttpMocker is a mocking library for third party HTTP clients, so it depends on OkHttp (as of v1.3.0, HttpMocker uses OkHttp 4 API, previous versions used OkHttp 3) or Ktor (v1.5.0), depending on which implementation you chose.
- It also uses SLF4J API for logging.
- JSON parsers depend on their respective external libraries: Jackson, Gson, Moshi or KotlinX serialization.
Proguard rules
Since Jackson, Gson or Kotlinx serialization use some type of introspection or annotation processing to parse JSON streams, it is recommended to keep the mapping classes unobfuscated. You can refer to those libraries recommendations and to the proguard-rules.pro file included in the demo app for an example of required rules.
The custom and moshi parsers are immune to obfuscation because they do not use any introspection.
Quickstart
Setting up HttpMocker with OkHttp
Mocking HTTP calls relies on a simple Interceptor: MockResponseInterceptor. All you need to set it up
is to add it to your OkHttp client. Here's an example with minimal configuration of dynamic mocks
(this configuration will respond to every request with a HTTP 200 Ok code and a body containing
only Fake response body)
- Java-friendly builder syntax:
val interceptor = Builder()
.useDynamicMocks {
ResponseDescriptor(code = 200, body = "Fake response body")
}
.setMode(ENABLED)
.build()
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
- Kotlin DSL syntax:
val interceptor = mockInterceptor {
useDynamicMocks {
ResponseDescriptor(code = 200, body = "Fake response body")
}
setMode(ENABLED)
}
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
Setting up HttpMocker with Ktor
Mocking HTTP calls relies on a HTTP client that will include two engines: one for actual network calls and one for mocked
calls. The syntax to create this client is very similar to the one for the standard HTTP client, but uses a
mockableHttpClient builder instead of the usual httpClient. You can keep all your usual configuration and just add
the mock configuration inside a mock section. Here is an example that shows how the mock configuration is added to a
regular Ktor client (with a CIO engine and JSON parsing with Kotlinx Serialization):
val client = mockableHttpClient(CIO) {
// This part defines the mock configuration to use
mock {
useDynamicMocks {
ResponseDescriptor(code = 200, body = "Fake response body")
}
setMode(ENABLED)
}
// Here is the rest of your standard HTTP Configuration
install(JsonFeature) {
serializer = KotlinxSerializer()
}
expectSuccess = false
followRedirects = false
}
General use
HttpMocker supports four modes:
- Disabled
- Enabled
- Mixed
- Record
You can set that mode when initializing your mocker object (if not, it is disabled by default), but you can also change its value dynamically later on.
// For OkHttp, you can change the mode directly in your interceptor:
interceptor.mode = ENABLED
// For Ktor, you will need to access the engine configuration:
(client.engine as MockEngine).mode = ENABLED
If your mocker is disabled, it will not interfere with actual network calls. If it is enabled,
it will need to find scenarios to mock the HTTP calls. Dynamic mocks imply that you have to
provide the response for each request programmatically, which allows you to define stateful
responses (identical calls could lead to different answers based on what the user did in between
these calls, or on any other external parameter you want to use: time, location...). The response
can be provided as a ResponseDescriptor by implementing the RequestCallback interface, or you
can simply provide a lambda function to do the computation.
NB: If you use dynamic mocks, the bodyFile attribute of your ResponseDescriptor is not needed (it
will be ignored). Its only use is for static scenarios that could save the response body in a separate
file (it keeps things clearer by not including the response file mixed with the scenario).
Another option is to use static mocks. Static mocks are scenarios stored as static files. Here is an example for an Android app using static mocks, with a few more options:
// For OkHttp:
val interceptor = mockInterceptor {
parseScenariosWith(mapper)
Related Skills
node-connect
337.3kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
83.2kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
337.3kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
83.2kCommit, push, and open a PR
