thanks a lot for getting back to me regarding my question.
I am using exactly that MockNetworkTransport from GitHub from your sample. I need to mock the ApolloResponse for my unit tests. That “mocked behavior” I put to an ApolloClient for my tests. My class which mocks the apollo client looks like this atm:
class ApolloRequestClientMock {
private var networkTransport: MockNetworkTransport = MockNetworkTransport()
fun simpleApolloClient(headers: Map<String, String>?): ApolloClient {
return ApolloClient(
networkTransport = networkTransport,
// The 'TestLoggerExecutor' is the one from GitHub
// https://github.com/apollographql/apollo-android/blob/main/apollo-runtime-kotlin/src/commonTest/kotlin/com/apollographql/apollo/mock/TestLoggerExecutor.kt
interceptors = listOf(TestLoggerExecutor)
)
}
fun setExpectedSuccessForNetworkTransportWith(responseJson: String) {
networkTransport.trySend(responseJson).isSuccess
}
fun setExpectedFailureForNetworkTransportBecauseDataEmpty() {
networkTransport.trySend("").isFailure
}
fun setExpectedFailureForNetworkTransportWith(failureResponse: String) {
networkTransport.trySend(failureResponse).isFailure
}
}
If the ApolloResponse does not contain a header named __typename I receive this error when executing my tests:
java.lang.NullPointerException: corrupted response reader, expected non null value for __typename
To have this __typename header I added a little bit of code to the MockNetworkTransport, regarding your answer and now the class is looking like this
@ApolloExperimental
@ExperimentalCoroutinesApi
internal class MockNetworkTransport(
private val mockResponseChannel: Channel<String> = Channel(capacity = Channel.BUFFERED)
) : NetworkTransport, SendChannel<String> by mockResponseChannel {
private var expectedStatusCode: Int = 200
private var expectedHeaders: Map<String, String> = mapOf("__typename" to "some-typename")
override fun <D : Operation.Data> execute(
request: ApolloRequest<D>,
executionContext: ExecutionContext
): Flow<ApolloResponse<D>> {
return flow {
emit(
ApolloResponse(
requestUuid = request.requestUuid,
response = request.operation.parse(mockResponseChannel.receive().encodeUtf8()),
executionContext = request.executionContext + HttpExecutionContext.Response(
statusCode = expectedStatusCode,
headers = expectedHeaders
)
)
)
}
}
fun setExpected(statusCode: Int) {
expectedStatusCode = statusCode
}
}
But it still does not work, I receive the same error of missing __typename. Is there anything I can change in my code to make it work?
I fixed the issue. It wasn’t about the header . This __typename should be in the response body and not in the header - for some reasons I thought that this field belongs in the header. Beginner issue.
So this one is solved. With the sample mock code from Martin writing unit tests for amp by mocking the ApolloClient works great