alichur
alichur

Reputation: 963

How best to stub/mock rest API calls in Flutter Integration tests

I have a Flutter app that displays data after the user logs in. I have unit and widget tests and now would like to write my first Integration/end-to-end test to test an entire 'happy path' workflow where the user logs in and views the data.

When the app goes to call the login API (GET login_api_path) I want to return some predefined JSON for what to show on the screen rather than making a real request to the server.

Is this a sensible approach, and if so what is the best way to do this? Most resources I found were specifically for unit testing.

Upvotes: 11

Views: 9633

Answers (1)

alichur
alichur

Reputation: 963

Here's the approach I went with:

Create a mock client that uses the Dart http MockClient:

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

MockClient integrationTestMockClient = MockClient((request) async {
  switch (request.url.toString()) {
    case 'https://staging.company.com/api/customer/123':
      return Response('{"customer": "123", "name": "Jane Jimmy"}', 200);
    case 'https://staging.company.com/api/customer/155':
      return Response('{"customer": "155", "name": "Gregor"}', 200);
  }
}

Now you need to pass your mock client into your app, when you start up your app in integration tests e.g. test_driver/app.dart

import 'mock_client.dart';

void main() async {
  enableFlutterDriverExtension();
  final app = await initializeApp(
    integrationMockClient,
  );
  runApp(app);
}

You may need to refactor your non-test code so that when the app starts up, you can inject a client. Either a real client or a mock client when testing.

import 'package:http/http.dart';

void main() => initializeApp(Client());

Upvotes: 13

Related Questions