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 =

    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();

          .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 =


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


  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.


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() {

  final MockClient client = MockClient();
  // make your mocks here
  httpClient = client;


Answered By – Felipe Augusto

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.