Hello! Is there any way to unit test the `isFromCa...
# apollo-kotlin
m
Hello! Is there any way to unit test the
isFromCache
property on a KMP project in
commonTest
without building a wrapper? I have tried using
MockServer
and
MockResponse
, but I see nothing cache-related there. Silly implementation example:
Copy code
class DataSource(private val apolloClient: ApolloClient) {

    suspend fun getResponse(): CustomObj {
        val response = apolloClient
            .query(RandomQuery())
            .fetchPolicy(FetchPolicy.NetworkFirst)
            .execute()

        val isFromCache = response.isFromCache
        
        return CustomObj(
            isCache = isFromCache,
            data = // parsing data
        )
    }
}
I want to be able to mock the
isFromCache
in the Apollo responses of my unit tests. I have also tried building my own mock Apollo response like this:
Copy code
val isFromCache = true        
val executionContext = mock<ExecutionContext>() {
    every { get(CacheInfo) } returns CacheInfo.Builder()
        .cacheHit(isFromCache)
        .build()
}

return ApolloResponse.Builder(
    operation = mock<Operation<GetTodayTabQuery.Data>>(),
    requestUuid = uuid4()
)
.data(mockData)
.addExecutionContext(executionContext)
.build()
However, I'm not sure you can use
MockServer
to return a real
ApolloResponse
object (just a
MockResponse
).
m
You can mock the
NetworkTransport
I think? This is what returns an
ApolloResponse
MockServer
works at the HTTP layer,
NetworkTransport
at the GraphQL layer
m
Thanks! That worked. For anyone's future reference, this is how I mocked the client and the network transport to change the
isFromCache
property:
Copy code
private fun createMockApolloClient(
        timestamp: Double,
        isFromCache: Boolean,
) = ApolloClient.Builder()
        .networkTransport(CustomTestNetworkTransport(timestamp, isFromCache))
        .build()

private class CustomTestNetworkTransport(
    private val timestamp: Double,
    private val isFromCache: Boolean,
) : NetworkTransport {
    override fun <D : Operation.Data> execute(request: ApolloRequest<D>): Flow<ApolloResponse<D>> = flowOf(
        createMockApolloResponseFromCache() as ApolloResponse<D>
    )

    override fun dispose() {}

    private fun createMockApolloResponseFromCache(): ApolloResponse<RandomQuery.Data> {
        val mockQuery = getMockResponse(timestamp)

        val executionContext = mock<ExecutionContext> {
            every { get(CacheInfo) } returns CacheInfo.Builder()
                .cacheHit(isFromCache)
                .build()
        }

        return ApolloResponse.Builder(
            operation = mock<Operation<RandomQuery.Data>>(),
            requestUuid = uuid4()
        )
            .data(mockQuery)
            .addExecutionContext(executionContext)
            .build()
    }
}