Kotlin: Compare MockRequest to a Specific Query

We have test setup with MockWebServer that basically fake most of the backend and issue some specific json based on which endpoint we request.

in case of /users/1 we return a valid user data
in case of /user/2 we return a invalid user data

I was trying to perform the same thing with Apollo Kotlin, where check if a given MockRequest is the same as an auto generated Query, so I can reply with correct json.

Anyone has an idea how to make this validation?

        val mockServer = MockServer(object : MockServerHandler {
            override fun handle(request: MockRequest): MockResponse {
                return when {
                    // Check if request is GetCharacterQuery query
                    request.isQuery(GetCharacterQuery("12345")) -> MockResponse(
                        body = """{"data": "Some data"}""",
                        headers = mapOf("X-Test" to "true"),
                    )
                    else -> MockResponse(statusCode = 404)
                }
            }
        })
        val apolloClient = ApolloClient.Builder().serverUrl(mockServer.url()).build()
        val response1 = apolloClient
            .query(GetCharacterQuery("12345"))
            .execute()

Thanks in advance.

Hi! :wave:

One thing you could do if you want to stay at the HTTP level, is to look at the X-APOLLO-OPERATION-ID header in the MockRequest, which value will be equal to the OPERATION_ID constant generated in the Query objects, so you could use that to distinguish them.

However, you could also mock the GraphQL responses instead by using a test network transport, as described here. With this you can map the operation to the response, which may be easier for what you want to do.

1 Like