Marcel
01/17/2025, 11:13 AMisFromCache
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:
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:
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
).mbonnin
01/17/2025, 2:04 PMNetworkTransport
I think? This is what returns an ApolloResponse
mbonnin
01/17/2025, 2:05 PMMockServer
works at the HTTP layer, NetworkTransport
at the GraphQL layerMarcel
01/27/2025, 12:20 PMisFromCache
property:
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()
}
}