You are viewing documentation for a previous version of this software.

Switch to the latest stable version.

Mocking HTTP responses (experimental)


ℹ️ MockServer is still experimental and most of the APIs are designed for Kotlin. MockServer is multiplatform but if you're using Java only, we recommend using OkHttp MockWebServer which will provide idiomatic Java APIs.

MockServer implements an HTTP server that you can use to mock responses. It's useful for testing specific server behaviors, such as error cases, HTTP headers, and timeouts. Using it requires minimal changes to your production code, because you only need to change your serverUrl.

See also TestNetworkTransport, which handles mocking at the GraphQL level instead of the HTTP level.

Add the dependency to your project's build.gradle file:

Kotlin
build.gradle[.kts]
1dependencies {
2  testImplementation("com.apollographql.apollo3:apollo-mockserver:3.8.5")
3}

And here's how to use it:

Kotlin
1// Create a mock server
2val mockServer = MockServer()
3
4// Provide its URL to your ApolloClient
5val apolloClient = ApolloClient.Builder().serverUrl(mockServer.url()).store(store).build()
6
7// Enqueue HTTP responses
8mockServer.enqueue("""{"data": {"random": 42}}""")
9mockServer.enqueue(
10    MockResponse(
11        body = "Internal server error",
12        statusCode = 500,
13        headers = mapOf("X-Test" to "true"),
14        // Optionally pass a delay to simulate network latency
15        delayMillis = 1000L,
16    )
17)
18
19// Execute queries
20val response1 = apolloClient
21    .query(GetRandomQuery())
22    .execute()
23
24val response2 = apolloClient
25    .query(GetRandomQuery())
26    .execute()
27
28// Don't forget to stop the server when you're done
29mockServer.stop()

The enqueue function normally takes a MockResponse as a parameter, but it also supports a shorthand version that takes a String (both are shown above).

Advanced usage

By default, MockServer is configured with a QueueMockServerHandler, which returns responses in the order they've been enqueued. If you need more control over the responses to return, you can implement your own MockServerHandler and pass it to the MockServer:

Kotlin
1val customHandler = object : MockServerHandler {
2  override fun handle(request: MockRequest): MockResponse {
3    return if (/* Your custom logic here */) {
4      MockResponse(
5          body = """{"data": {"random": 42}}""",
6          headers = mapOf("X-Test" to "true"),
7      )
8    } else {
9      MockResponse(
10          body = "Internal server error",
11          statusCode = 500,
12      )
13    }
14  }
15}
16
17val mockServer = MockServer(customHandler)

Note that if you use a custom MockServerHandler, calling MockServer.enqueue() is no longer possible because it expects the handler to be a QueueMockServerHandler.

Feedback

Edit on GitHub

Forums