Skip to content

appunite/MockWebServer-Extensions

Repository files navigation

MockWebServer Extensions

The MockWebServer Extensions, provides a convenient solution for testing HTTP clients by extending MockWebServer functionalities. With easy integration into your testing environment, it allows for seamless mocking of server responses, facilitating comprehensive testing of HTTP client behaviors.

Usage

Create a variable with MockWebServerRule in the test class.

@get:Rule
var mockWebServer: MockWebServerRule = MockWebServerRule()

To mock a request, use register method.

mockWebServer.register {
    expectThat(it).url.path.isEqualTo("/fact")
    jsonResponse("""{"fact": "Example fact about your cat."}""")
}

Requirements

Download

Add it in your root build.gradle at the end of repositories or in settings.gradle:

repositories {
    maven { url 'https://jitpack.io' }
}

Add the dependency:

dependencies {
    androidTestImplementation 'com.github.appunite.MockWebServer-Extensions:mockwebserver-extensions:0.2.2'
    androidTestImplementation 'com.github.appunite.MockWebServer-Extensions:mockwebserver-request:0.2.2'
    implementation 'com.github.appunite.MockWebServer-Extensions:mockwebserver-interceptor:0.2.2'
}

Add a Network Security Configuration

dependencies {
    debugImplementation 'com.github.appunite.MockWebServer-Extensions:mockwebserver-allow-mocking:0.2.2'
}

Add TestInterceptor to your HTTP Client.

// Ktor
val client = HttpClient(OkHttp) {
    engine {
        addInterceptor(TestInterceptor)
    }
}

// Retrofit
val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(TestInterceptor)
    .build()

val retrofit = Retrofit.Builder()
    .baseUrl(baseUrl)
    .client(okHttpClient)
    .build()

Optional Assertions using okhttp

dependencies {
    androidTestImplementation 'com.github.appunite.MockWebServer-Extensions:mockwebserver-assertions:0.2.2'
}

You can check full example in the app module. And more examples in the Loudius - Android playground in the app-shared-tests module.

License

Copyright 2024 Appunite

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.