I have a problem when testing my classes that make http requests. I want to Mock the client so that every time the client makes a request, I can answer with a Mocked response. At the moment my code looks like this:
final fn = MockClientHandler;
final client = MockClient(fn as Future<Response> Function(Request));
when(client.get(url)).thenAnswer((realInvocation) async =>
http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
However, when I run the test I get the following exception:
type '_FunctionType' is not a subtype of type '(Request) => Future<Response>' in type cast test/data_retrieval/sources/fitbit_test.dart 26:32 main
According to Flutter/Dart Mockito should be used like this:
final client = MockClient();
// Use Mockito to return a successful response when it calls the
// provided http.Client.
when(client.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')))
.thenAnswer((_) async => http.Response('{"userId": 1, "id": 2, "title":"mock"}', 200));
In the example, the client is mocked without parameters, but I guess this has been changed since the documentation of MockClient now also accepts a parameter. I have no idea why this exception occurs and nothing can be found on the internet, so I was wondering if someone here knows why this exception is happening.
package:http'sMockClientis a bit of a misnomer. It's not really a mock (and it's certainly not related topackage:mockito'sMock); it's more like a stub (or arguably a fake): it has an implementation that is meant to simulate a normalhttp.Clientobject.Note that Flutter's Mockito examples create a
MockClientobject usingpackage:mockito, but this is unrelated to theMockClientclass provided bypackage:httpitself.package:http'sMockClientexpects an instance of aMockClientHandleras an argument, but you are attempting to pass theMockClientHandlertype itself. You are expected to provide an actual function (again, becauseMockClienthas an actual implementation).In other words, if you want to use
package:http'sMockClient, then you should do:Or if you want to use
package:mockito, you need to follow https://flutter.dev/docs/cookbook/testing/unit/mocking exactly and generate a Mockito-basedMockClientclass.