GraphQL Summit is back for three days of insights, hands-on learning, and fun to celebrate the GraphQL community. Join us in San Diego Oct 3-5.
Try Apollo Studio

Mocking GraphQL responses (experimental)

QueueTestNetworkTransport is a high-level test API that enables you to specify the GraphQL responses that are returned by your ApolloClient instance.

See also MockServer, which creates a full HTTP server and helps test specific server behaviors, such as error cases, HTTP headers, and timeouts.

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

dependencies {
// Also add jcenter() to your repositories
// See
repositories {

Enable the QueueTestNetworkTransport by passing it to the ApolloClient builder:

val apolloClient = ApolloClient.Builder()

You can then use the enqueueTestResponse extension function to specify the GraphQL responses to return:

val testQuery = GetHeroQuery("001")
val testData = GetHeroQuery.Data {
hero = droidHero {
name = "R2D2"
apolloClient.enqueueTestResponse(testQuery, testData)
val actual = apolloClient.query(testQuery).execute().data!!

You can pass an ApolloResponse to the enqueueTestResponse function, or as a shortcut, you can pass a Data directly as shown above. If you do pass a Data, you also need to pass an operation, because an ApolloResponse is built under the hood, which needs a reference to it.

To help create your mocked response data, you can use test builders.

Advanced usage

QueueTestNetworkTransport returns responses in the order they've been enqueued.

In certain tests, it might be more convenient to map responses to operations.

To achieve this, use MapTestNetworkTransport instead and call the registerTestResponse extension function:

val apolloClient = ApolloClient.Builder().networkTransport(MapTestNetworkTransport()).build()
apolloClient.registerTestResponse(query1, testData1)
apolloClient.registerTestResponse(query2, testData2)
val actual1 = apolloClient.query(query1).execute().data
val actual2 = apolloClient.query(query2).execute().data
// Execute query1 again, which is mapped to testData1
val actual3 = apolloClient.query(query1).execute().data
assertEquals(testData1, actual1)
assertEquals(testData2, actual2)
assertEquals(testData1, actual3)

If you need more control over the responses to return, you can implement your own NetworkTransport and pass it to the ApolloClient builder:

private class CustomTestNetworkTransport : NetworkTransport {
override fun <D : Operation.Data> execute(request: ApolloRequest<D>): Flow<ApolloResponse<D>> {
return flowOf(
/* Your custom logic here */
).build() as ApolloResponse<D>
override fun dispose() {}
apolloClient = ApolloClient.Builder()

Note that if you use a custom NetworkTransport, calling enqueueTestResponse() or registerTestResponse() is no longer possible because they expect the transport to be QueueTestNetworkTransport or MapTestNetworkTransport.

Edit on GitHub
Mocking HTTP responses
Data builders