Search code examples
dartfluttermockingmockitoflutter-test

How to mock http request in flutter integration test?


I'm trying to do so using Mockito, this is my test:

import 'package:http/http.dart' as http;
import 'package:utgard/globals.dart' as globals;
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
import 'package:mockito/mockito.dart';

class MockClient extends Mock implements http.Client {}

void main() {
  group('Login flow', () {

    final SerializableFinder loginContinuePasswordButton =
        find.byValueKey('login_continue_password_button');

    FlutterDriver driver;

    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        //await driver.close();
      }
    });


    test('login with correct password', () async {
      final client = MockClient();

      when(client.post('http://wwww.google.com'))
          .thenAnswer((_) async => http.Response('{"title": "Test"}', 200));

      globals.httpClient = client;

      await driver.enterText('000000');
      await driver.tap(loginContinuePasswordButton);
    });
  });
}

And this is my http request code:

Future<Map<String, dynamic>> post({
  RequestType requestType,
  Map<String, dynamic> body,
}) async {
  final http.Response response =
      await globals.httpClient.post('http://wwww.google.com');

  print(response);

  final Map<String, dynamic> finalResponse = buildResponse(response);

  _managerErrors(finalResponse);

  return finalResponse;
}

And here I have the global:

library utgard.globals;

import 'package:http/http.dart' as http;

http.Client httpClient = http.Client();

However I continue to receive http errors, that indicates to me that the http wasn't replaced by the mock.


Solution

  • The solution I found was to define the mock in test_driver/app.dart and call the runApp function after that:

    import 'package:flutter/widgets.dart';
    import 'package:flutter_driver/driver_extension.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import 'package:utgard/business/config/globals.dart';
    import 'package:utgard/main.dart' as app;
    
    class MockClient extends Mock implements http.Client {}
    
    void main() {
      enableFlutterDriverExtension();
    
      final MockClient client = MockClient();
      // make your mocks here
      httpClient = client;
    
      runApp(app.MyApp());
    }