Mockito http.Client type 'Null' is not a subtype of type 'Future<Response>' in type cast
138
So the solution was to use the MockClient class provided by package:http, and not use mockito.
group('post Gdpr success', () {
Future<http.Response> requestHandler(http.Request request) async {
final apiResponse = fixture('gdpr_response.json');
return http.Response(apiResponse, 201);
}
setUp(() {
mockHttpClient = MockClient(requestHandler);
dataSource = GdprDataSourceImpl(
httpClient: mockHttpClient,
baseUrl: '',
);
});
test('should perform a POST request to /gdpr/consent', () async {
final result = await dataSource.postGdpr(status: status);
expect(result, gdprResponse);
});
});
Author by
Chedi Athmni
Updated on January 03, 2023Comments
-
Chedi Athmni 10 months
I'm applying a unit test over a http request in a Flutter application using Mockito.
Code to be tested:
@GenerateMocks([http.Client]) void main() { late GdprDataSourceImpl dataSource; late MockClient mockHttpClient; setUp(() { mockHttpClient = MockClient(); dataSource = GdprDataSourceImpl( httpClient: mockHttpClient, baseUrl: '', ); }); group('post Gdpr', () { const status = true; final url = Uri.parse('/gdpr/consent'); const body = { 'status': status, }; final errorMessage = fixture('error_response.json'); test('should perform a POST request to /auth/otp', () async { when(mockHttpClient.post(url, body: body)).thenAnswer( (_) async => http.Response('', 201), ); await dataSource.postGdpr(status: status); verify(mockHttpClient.post(url, body: body)); }); }); }
And I'm getting the following error: type 'Null' is not a subtype of type 'Future' in type cast
Mocks have been successfully generated with the build runner
I also tried updating the mocked class and change the return value to
returnValue: Future<http.Response?>
I get: type 'Future<Response?>' is not a subtype of type 'Future' in type cast
-
jamesdlin over 1 yearWhat is the stack trace from the error? Which line is it referring to? Are you sure that there isn't a method on the
http.Client
that you neglected to stub? Are you sure that you created a stub with the correct arguments? (TheUri
looks wrong.) Also, is there a reason why you're generating a mockhttp.Client
yourself instead of using theMockClient
class provided bypackage:http
? -
Chedi Athmni over 1 yearthanks for the answer, I switech to using the MockClient class by package:http and now I'm getting as error Bad state: No method stub was called from within
when()
. Was a real method called, or perhaps an extension method?
-